-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_inputs.py
More file actions
814 lines (723 loc) · 28.2 KB
/
test_inputs.py
File metadata and controls
814 lines (723 loc) · 28.2 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
"""Test the inputs module."""
import pathlib
import pickle
import tempfile
from unittest.mock import patch
import numpy as np
import pytest
import ratapi
import ratapi.wrappers
from ratapi.inputs import FileHandles, check_indices, make_controls, make_input, make_problem
from ratapi.rat_core import Checks, Control, NameStore, ProblemDefinition
from ratapi.utils.enums import (
BackgroundActions,
BoundHandling,
Calculations,
Display,
Geometries,
LayerModels,
Parallel,
Procedures,
)
from tests.utils import dummy_function
@pytest.fixture
def standard_layers_project():
"""Add parameters to the default project for a normal calculation."""
test_project = ratapi.Project(
data=ratapi.ClassList([ratapi.models.Data(name="Test Data", 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",
filename="python_test.py",
function_name="dummy_function",
language="python",
)
test_project.layers.append(
name="Test Layer",
thickness="Test Thickness",
SLD="Test SLD",
roughness="Test Roughness",
)
test_project.contrasts.append(
name="Test Contrast",
data="Test Data",
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 domains_project():
"""Add parameters to the default project for a domains calculation."""
test_project = ratapi.Project(
calculation=Calculations.Domains,
data=ratapi.ClassList([ratapi.models.Data(name="Test Data", 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", filename="matlab_test.m", language="matlab")
test_project.layers.append(
name="Test Layer",
thickness="Test Thickness",
SLD="Test SLD",
roughness="Test Roughness",
)
test_project.domain_contrasts.append(name="up", model=["Test Layer"])
test_project.domain_contrasts.append(name="down", model=["Test Layer"])
test_project.contrasts.append(
name="Test Contrast",
data="Test Data",
background="Background 1",
bulk_in="SLD Air",
bulk_out="SLD D2O",
scalefactor="Scalefactor 1",
resolution="Resolution 1",
domain_ratio="Domain Ratio 1",
model=["down", "up"],
)
return test_project
@pytest.fixture
def custom_xy_project():
"""Add parameters to the default project for a normal calculation and use the custom xy model."""
test_project = ratapi.Project(model=LayerModels.CustomXY)
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", filename="cpp_test.dll", language="cpp")
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 Custom File"],
)
return test_project
@pytest.fixture
def test_names():
"""The expected NameStore object from "standard_layers_project", "domains_project" and "custom_xy_project"."""
names = NameStore()
names.params = ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"]
names.backgroundParams = ["Background Param 1"]
names.scalefactors = ["Scalefactor 1"]
names.bulkIns = ["SLD Air"]
names.bulkOuts = ["SLD D2O"]
names.resolutionParams = ["Resolution Param 1"]
names.domainRatios = []
names.contrasts = ["Test Contrast"]
return names
@pytest.fixture
def test_checks():
"""The expected checks object from "standard_layers_project", "domains_project" and "custom_xy_project"."""
checks = Checks()
checks.params = np.array([1, 0, 0, 0])
checks.backgroundParams = np.array([0])
checks.scalefactors = np.array([0])
checks.bulkIns = np.array([0])
checks.bulkOuts = np.array([0])
checks.resolutionParams = np.array([0])
checks.domainRatios = np.array([])
return checks
@pytest.fixture
def standard_layers_problem(test_names, test_checks):
"""The expected problem object from "standard_layers_project"."""
problem = ProblemDefinition()
problem.TF = Calculations.Normal
problem.modelType = LayerModels.StandardLayers
problem.geometry = Geometries.AirSubstrate
problem.useImaginary = False
problem.params = [3.0, 0.0, 0.0, 0.0]
problem.bulkIns = [0.0]
problem.bulkOuts = [6.35e-06]
problem.scalefactors = [0.23]
problem.domainRatios = []
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [[1]]
problem.contrastBackgroundActions = [BackgroundActions.Add]
problem.contrastBackgroundTypes = ["constant"]
problem.contrastResolutionParams = [[1]]
problem.contrastResolutionTypes = ["constant"]
problem.contrastCustomFiles = [float("NaN")]
problem.contrastDomainRatios = [0]
problem.resample = [False]
problem.dataPresent = [1]
problem.data = [np.array([[1.0, 1.0, 1.0, 0.0, 0.0, 0.0]])]
problem.dataLimits = [[1.0, 1.0]]
problem.simulationLimits = [[1.0, 1.0]]
problem.numberOfContrasts = 1
problem.numberOfLayers = 1
problem.repeatLayers = [1]
problem.layersDetails = [[2, 3, 4, float("NaN"), 1]]
problem.contrastLayers = [[1]]
problem.numberOfDomainContrasts = 0
problem.domainContrastLayers = []
problem.fitParams = [3.0]
problem.fitLimits = [[1.0, 5.0]]
problem.priorNames = [
"Substrate Roughness",
"Test Thickness",
"Test SLD",
"Test Roughness",
"Background Param 1",
"Scalefactor 1",
"SLD Air",
"SLD D2O",
"Resolution Param 1",
]
problem.priorValues = [
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
]
problem.customFiles = FileHandles([])
problem.names = test_names
problem.checks = test_checks
return problem
@pytest.fixture
def domains_problem(test_names, test_checks):
"""The expected problem object from "domains_project"."""
problem = ProblemDefinition()
problem.TF = Calculations.Domains
problem.modelType = LayerModels.StandardLayers
problem.geometry = Geometries.AirSubstrate
problem.useImaginary = False
problem.params = [3.0, 0.0, 0.0, 0.0]
problem.bulkIns = [0.0]
problem.bulkOuts = [6.35e-06]
problem.scalefactors = [0.23]
problem.domainRatios = [0.5]
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [[1]]
problem.contrastBackgroundActions = [BackgroundActions.Add]
problem.contrastBackgroundTypes = ["constant"]
problem.contrastResolutionParams = [[1]]
problem.contrastResolutionTypes = ["constant"]
problem.contrastCustomFiles = [float("NaN")]
problem.contrastDomainRatios = [1]
problem.resample = [False]
problem.dataPresent = [1]
problem.data = [np.array([[1.0, 1.0, 1.0, 0.0, 0.0, 0.0]])]
problem.dataLimits = [[1.0, 1.0]]
problem.simulationLimits = [[1.0, 1.0]]
problem.numberOfContrasts = 1
problem.numberOfLayers = 1
problem.repeatLayers = [1]
problem.layersDetails = [[2, 3, 4, float("NaN"), 1]]
problem.contrastLayers = [[2, 1]]
problem.numberOfDomainContrasts = 2
problem.domainContrastLayers = [[1], [1]]
problem.fitParams = [3.0]
problem.fitLimits = [[1.0, 5.0]]
problem.priorNames = [
"Substrate Roughness",
"Test Thickness",
"Test SLD",
"Test Roughness",
"Background Param 1",
"Scalefactor 1",
"SLD Air",
"SLD D2O",
"Resolution Param 1",
"Domain Ratio 1",
]
problem.priorValues = [
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
]
problem.customFiles = FileHandles([])
problem.names = test_names
problem.names.domainRatios = ["Domain Ratio 1"]
problem.checks = test_checks
return problem
@pytest.fixture
def custom_xy_problem(test_names, test_checks):
"""The expected problem object from "custom_xy_project"."""
problem = ProblemDefinition()
problem.TF = Calculations.Normal
problem.modelType = LayerModels.CustomXY
problem.geometry = Geometries.AirSubstrate
problem.useImaginary = False
problem.params = [3.0, 0.0, 0.0, 0.0]
problem.bulkIns = [0.0]
problem.bulkOuts = [6.35e-06]
problem.scalefactors = [0.23]
problem.domainRatios = []
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [[1]]
problem.contrastBackgroundActions = [BackgroundActions.Add]
problem.contrastBackgroundTypes = ["constant"]
problem.contrastResolutionParams = [[1]]
problem.contrastResolutionTypes = ["constant"]
problem.contrastCustomFiles = [1]
problem.contrastDomainRatios = [0]
problem.resample = [True]
problem.dataPresent = [0]
problem.data = [np.empty([0, 6])]
problem.dataLimits = [[0.0, 0.0]]
problem.simulationLimits = [[0.005, 0.7]]
problem.repeatLayers = [1]
problem.layersDetails = []
problem.contrastLayers = [[]]
problem.numberOfContrasts = 1
problem.numberOfLayers = 0
problem.numberOfDomainContrasts = 0
problem.domainContrastLayers = []
problem.fitParams = [3.0]
problem.fitLimits = [[1.0, 5.0]]
problem.priorNames = [
"Substrate Roughness",
"Test Thickness",
"Test SLD",
"Test Roughness",
"Background Param 1",
"Scalefactor 1",
"SLD Air",
"SLD D2O",
"Resolution Param 1",
]
problem.priorValues = [
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
[1, 0.0, np.inf],
]
problem.customFiles = FileHandles(
[ratapi.models.CustomFile(name="Test Custom File", filename="cpp_test.dll", language="cpp")]
)
problem.names = test_names
problem.checks = test_checks
return problem
@pytest.fixture
def standard_layers_controls():
"""The expected controls object for input to the compiled RAT code given the default inputs and
"standard_layers_project".
"""
controls = Control()
controls.procedure = Procedures.Calculate
controls.parallel = Parallel.Single
controls.numSimulationPoints = 500
controls.resampleMinAngle = 0.9
controls.resampleNPoints = 50
controls.display = Display.Iter
controls.xTolerance = 1.0e-6
controls.funcTolerance = 1.0e-6
controls.maxFuncEvals = 10000
controls.maxIterations = 1000
controls.updateFreq = 1
controls.updatePlotFreq = 20
controls.populationSize = 20
controls.fWeight = 0.5
controls.crossoverProbability = 0.8
controls.strategy = 4
controls.targetValue = 1.0
controls.numGenerations = 500
controls.nLive = 150
controls.nMCMC = 0.0
controls.propScale = 0.1
controls.nsTolerance = 0.1
controls.nSamples = 20000
controls.nChains = 10
controls.jumpProbability = 0.5
controls.pUnitGamma = 0.2
controls.boundHandling = BoundHandling.Reflect
controls.adaptPCR = True
return controls
@pytest.fixture
def custom_xy_controls():
"""The expected controls object for input to the compiled RAT code given the default inputs and
"custom_xy_project".
"""
controls = Control()
controls.procedure = Procedures.Calculate
controls.parallel = Parallel.Single
controls.numSimulationPoints = 500
controls.resampleMinAngle = 0.9
controls.resampleNPoints = 50.0
controls.display = Display.Iter
controls.xTolerance = 1.0e-6
controls.funcTolerance = 1.0e-6
controls.maxFuncEvals = 10000
controls.maxIterations = 1000
controls.updateFreq = 1
controls.updatePlotFreq = 20
controls.populationSize = 20
controls.fWeight = 0.5
controls.crossoverProbability = 0.8
controls.strategy = 4
controls.targetValue = 1.0
controls.numGenerations = 500
controls.nLive = 150
controls.nMCMC = 0.0
controls.propScale = 0.1
controls.nsTolerance = 0.1
controls.nSamples = 20000
controls.nChains = 10
controls.jumpProbability = 0.5
controls.pUnitGamma = 0.2
controls.boundHandling = BoundHandling.Reflect
controls.adaptPCR = True
return controls
@pytest.mark.parametrize(
["test_project", "test_problem", "test_controls"],
[
(
"standard_layers_project",
"standard_layers_problem",
"standard_layers_controls",
),
(
"custom_xy_project",
"custom_xy_problem",
"custom_xy_controls",
),
(
"domains_project",
"domains_problem",
"standard_layers_controls",
),
],
)
def test_make_input(test_project, test_problem, test_controls, request) -> None:
"""When converting the "project" and "controls", we should obtain the two input objects required for the compiled
RAT code.
"""
test_project = request.getfixturevalue(test_project)
test_problem = request.getfixturevalue(test_problem)
test_controls = request.getfixturevalue(test_controls)
problem, controls = make_input(test_project, ratapi.Controls())
problem = pickle.loads(pickle.dumps(problem))
check_problem_equal(problem, test_problem)
controls = pickle.loads(pickle.dumps(controls))
check_controls_equal(controls, test_controls)
@pytest.mark.parametrize(
["test_project", "test_problem"],
[
("standard_layers_project", "standard_layers_problem"),
("custom_xy_project", "custom_xy_problem"),
("domains_project", "domains_problem"),
],
)
def test_make_problem(test_project, test_problem, request) -> None:
"""The problem object should contain the relevant parameters defined in the input project object."""
test_project = request.getfixturevalue(test_project)
test_problem = request.getfixturevalue(test_problem)
problem = make_problem(test_project)
check_problem_equal(problem, test_problem)
@pytest.mark.parametrize("test_problem", ["standard_layers_problem", "custom_xy_problem", "domains_problem"])
class TestCheckIndices:
"""Tests for check_indices over a set of three test problems."""
def test_check_indices(self, test_problem, request) -> None:
"""The check_indices routine should not raise errors for a properly defined ProblemDefinition object."""
test_problem = request.getfixturevalue(test_problem)
check_indices(test_problem)
@pytest.mark.parametrize(
"index_list",
[
"contrastBulkIns",
"contrastBulkOuts",
"contrastScalefactors",
"contrastDomainRatios",
],
)
@pytest.mark.parametrize("bad_value", ([0.0], [2.0]))
def test_check_indices_error(self, test_problem, index_list, bad_value, request) -> None:
"""The check_indices routine should raise an IndexError if a contrast list contains an index that is out of the
range of the corresponding parameter list in a ProblemDefinition object.
"""
param_list = {
"contrastBulkIns": "bulkIns",
"contrastBulkOuts": "bulkOuts",
"contrastScalefactors": "scalefactors",
"contrastDomainRatios": "domainRatios",
}
if (test_problem != "domains_problem") and (index_list == "contrastDomainRatios"):
# we expect this to not raise an error for non-domains problems as domainRatios is empty
pytest.xfail()
test_problem = request.getfixturevalue(test_problem)
setattr(test_problem, index_list, bad_value)
with pytest.raises(
IndexError,
match=f'The problem field "{index_list}" contains: {bad_value[0]}, which lies '
f'outside of the range of "{param_list[index_list]}"',
):
check_indices(test_problem)
@pytest.mark.parametrize("background_type", ["constant", "data", "function"])
@pytest.mark.parametrize("bad_value", ([[0.0]], [[2.0]]))
def test_background_params_source_indices(self, test_problem, background_type, bad_value, request):
"""check_indices should raise an IndexError for bad sources in the nested list contrastBackgroundParams."""
test_problem = request.getfixturevalue(test_problem)
test_problem.contrastBackgroundParams = bad_value
test_problem.contrastBackgroundTypes = [background_type]
source_param_lists = {
"constant": "backgroundParams",
"data": "data",
"function": "customFiles",
}
with pytest.raises(
IndexError,
match=f'Entry 0 of contrastBackgroundParams has type "{background_type}" '
f"and source index {bad_value[0][0]}, "
f'which is outside the range of "{source_param_lists[background_type]}".',
):
check_indices(test_problem)
@pytest.mark.parametrize(
"bad_value",
(
[[1.0, 0.0]],
[[1.0, 2.0]],
[[1.0, 1.0, 2.0]],
[[1.0], [1.0, 0.0]],
),
)
def test_background_params_value_indices(self, test_problem, bad_value, request):
"""check_indices should raise an IndexError for bad values in the nested list contrastBackgroundParams."""
test_problem = request.getfixturevalue(test_problem)
test_problem.contrastBackgroundParams = bad_value
if len(bad_value) > 1:
test_problem.contrastBackgroundTypes.append("constant")
with pytest.raises(
IndexError,
match=f"Entry {len(bad_value) - 1} of contrastBackgroundParams contains: {bad_value[-1][-1]}"
f', which lies outside of the range of "backgroundParams"',
):
check_indices(test_problem)
@pytest.mark.parametrize("test_project", ["standard_layers_project", "custom_xy_project", "domains_project"])
@pytest.mark.parametrize("field", ["data", "background", "bulk_in", "bulk_out", "scalefactor", "resolution"])
def test_undefined_contrast_fields(test_project, field, request):
"""If a field in a contrast is empty, we should raise an error."""
test_project = request.getfixturevalue(test_project)
setattr(test_project.contrasts[0], field, "")
with pytest.raises(
ValueError,
match=f'In the input project, the "{field}" field of contrast '
f'"{test_project.contrasts[0].name}" does not have a value defined. '
f"A value must be supplied before running the project.",
):
make_problem(test_project)
@pytest.mark.parametrize("test_project", ["standard_layers_project", "custom_xy_project", "domains_project"])
def test_undefined_background(test_project, request):
"""If the source field of a background defined in a contrast is empty, we should raise an error."""
test_project = request.getfixturevalue(test_project)
background = test_project.backgrounds[test_project.contrasts[0].background]
background.source = ""
with pytest.raises(
ValueError,
match=f"All backgrounds must have a source defined. For a {background.type} type "
f"background, the source must be defined in "
f'"{ratapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"',
):
make_problem(test_project)
@pytest.mark.parametrize("test_project", ["standard_layers_project", "custom_xy_project", "domains_project"])
def test_undefined_resolution(test_project, request):
"""If the source field of a resolution defined in a contrast is empty, we should raise an error."""
test_project = request.getfixturevalue(test_project)
resolution = test_project.resolutions[test_project.contrasts[0].resolution]
resolution.source = ""
with pytest.raises(
ValueError,
match=f"Constant resolutions must have a source defined. The source must be defined in "
f'"{ratapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"',
):
make_problem(test_project)
@pytest.mark.parametrize("test_project", ["standard_layers_project", "domains_project"])
@pytest.mark.parametrize("field", ["thickness", "SLD", "roughness"])
def test_undefined_layers(test_project, field, request):
"""If the thickness, SLD, or roughness fields of a layer defined in the project are empty, we should raise an
error."""
test_project = request.getfixturevalue(test_project)
setattr(test_project.layers[0], field, "")
with pytest.raises(
ValueError,
match=f'In the input project, the "{field}" field of layer {test_project.layers[0].name} '
f"does not have a value defined. A value must be supplied before running the project.",
):
make_problem(test_project)
def test_append_data_background():
"""Test that background data is correctly added to contrast data."""
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
background = np.array([[1, 10, 11], [4, 12, 13], [7, 14, 15]])
result = ratapi.inputs.append_data_background(data, background)
np.testing.assert_allclose(result, np.array([[1, 2, 3, 0, 10, 11], [4, 5, 6, 0, 12, 13], [7, 8, 9, 0, 14, 15]]))
def test_append_data_background_res():
"""Test that background data is correctly added to contrast data when a resolution is in the data."""
data = np.array([[1, 2, 3, 4], [4, 5, 6, 6], [7, 8, 9, 72]])
background = np.array([[1, 10, 11], [4, 12, 13], [7, 14, 15]])
result = ratapi.inputs.append_data_background(data, background)
np.testing.assert_allclose(result, np.array([[1, 2, 3, 4, 10, 11], [4, 5, 6, 6, 12, 13], [7, 8, 9, 72, 14, 15]]))
def test_append_data_background_error():
"""Test that append_data_background raises an error if the q-values are not equal."""
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
background = np.array([[56, 10, 11], [41, 12, 13], [7, 14, 15]])
with pytest.raises(ValueError, match=("The q-values of the data and background must be equal.")):
ratapi.inputs.append_data_background(data, background)
def test_get_python_handle():
path = pathlib.Path(__file__).parent
assert ratapi.inputs.get_python_handle("utils.py", "dummy_function", path).__code__ == dummy_function.__code__
def test_make_controls(standard_layers_controls) -> None:
"""The controls object should contain the full set of controls parameters, with the appropriate set defined by the
input controls.
"""
controls = make_controls(ratapi.Controls())
check_controls_equal(controls, standard_layers_controls)
@patch("ratapi.wrappers.MatlabWrapper")
def test_file_handles(wrapper):
handle = FileHandles([ratapi.models.CustomFile(name="Test Custom File", filename="cpp_test.dll", language="cpp")])
with pytest.raises(FileNotFoundError, match="The custom file \\(Test Custom File\\) does not have a valid path."):
handle.get_handle(0)
with tempfile.NamedTemporaryFile("w", suffix=".dll") as f:
tmp_file = pathlib.Path(f.name)
handle.files[0]["path"] = tmp_file.parent
handle.files[0]["filename"] = tmp_file.name
handle.files[0]["function_name"] = ""
# No function name should throw exception
with pytest.raises(
ValueError, match="The custom file \\(Test Custom File\\) does not have a valid function name."
):
handle.get_handle(0)
# Matlab does not need function name
handle.files[0]["language"] = "matlab"
handle.get_handle(0)
wrapper.assert_called()
def check_problem_equal(actual_problem, expected_problem) -> None:
"""Compare two instances of the "problem" object for equality."""
scalar_fields = [
"TF",
"modelType",
"geometry",
"useImaginary",
"numberOfContrasts",
"numberOfLayers",
"numberOfDomainContrasts",
"priorNames",
]
array_fields = [
"params",
"backgroundParams",
"scalefactors",
"bulkIns",
"bulkOuts",
"resolutionParams",
"domainRatios",
"contrastBackgroundParams",
"contrastBackgroundActions",
"contrastScalefactors",
"contrastBulkIns",
"contrastBulkOuts",
"contrastResolutionParams",
"contrastDomainRatios",
"resample",
"dataPresent",
"dataLimits",
"simulationLimits",
"repeatLayers",
"contrastLayers",
"domainContrastLayers",
"fitParams",
"fitLimits",
"priorValues",
]
checks_fields = [
"params",
"backgroundParams",
"scalefactors",
"bulkIns",
"bulkOuts",
"resolutionParams",
"domainRatios",
]
names_fields = [*checks_fields, "contrasts"]
for scalar_field in scalar_fields:
assert getattr(actual_problem, scalar_field) == getattr(expected_problem, scalar_field)
for array_field in array_fields:
assert np.all(getattr(actual_problem, array_field) == getattr(expected_problem, array_field))
for field in names_fields:
assert getattr(actual_problem.names, field) == getattr(expected_problem.names, field)
for field in checks_fields:
assert (getattr(actual_problem.checks, field) == getattr(expected_problem.checks, field)).all()
# Data field is a numpy array
assert [
actual_data == expected_data
for (actual_data, expected_data) in zip(actual_problem.data, expected_problem.data, strict=False)
]
# Need to account for "NaN" entries in layersDetails and contrastCustomFiles field
for actual_layer, expected_layer in zip(actual_problem.layersDetails, expected_problem.layersDetails, strict=False):
assert (actual_layer == expected_layer) or ["NaN" if np.isnan(el) else el for el in actual_layer] == [
"NaN" if np.isnan(el) else el for el in expected_layer
]
assert (actual_problem.contrastCustomFiles == expected_problem.contrastCustomFiles).all() or [
"NaN" if np.isnan(el) else el for el in actual_problem.contrastCustomFiles
] == ["NaN" if np.isnan(el) else el for el in expected_problem.contrastCustomFiles]
def check_controls_equal(actual_controls, expected_controls) -> None:
"""Compare two instances of the "controls" object used as input for the compiled RAT code for equality."""
controls_fields = [
"procedure",
"parallel",
"numSimulationPoints",
"resampleMinAngle",
"resampleNPoints",
"display",
"xTolerance",
"funcTolerance",
"maxFuncEvals",
"maxIterations",
"updateFreq",
"updatePlotFreq",
"populationSize",
"fWeight",
"crossoverProbability",
"strategy",
"targetValue",
"numGenerations",
"nLive",
"nMCMC",
"propScale",
"nsTolerance",
"nSamples",
"nChains",
"jumpProbability",
"pUnitGamma",
"boundHandling",
"adaptPCR",
]
for field in controls_fields:
assert getattr(actual_controls, field) == getattr(expected_controls, field)