Repository navigation
Expand file tree
/
Copy pathtest_inputs.py
More file actions
917 lines (828 loc) · 30.4 KB
/
Copy pathtest_inputs.py
File metadata and controls
917 lines (828 loc) · 30.4 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
"""Test the inputs module."""
import pathlib
import pickle
from itertools import chain
from unittest import mock
import numpy as np
import pytest
import RATapi
import RATapi.wrappers
from RATapi.inputs import check_indices, make_cells, make_controls, make_input, make_problem
from RATapi.rat_core import Cells, Checks, Control, Limits, Priors, ProblemDefinition
from RATapi.utils.enums import (
BoundHandling,
Calculations,
Display,
Geometries,
LayerModels,
Parallel,
Procedures,
TypeOptions,
)
from tests.utils import dummy_function
@pytest.fixture
def standard_layers_project():
"""Add parameters to the default project for a non polarised 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 non polarised 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 standard_layers_problem():
"""The expected problem object from "standard_layers_project"."""
problem = ProblemDefinition()
problem.TF = Calculations.NonPolarised
problem.modelType = LayerModels.StandardLayers
problem.geometry = Geometries.AirSubstrate
problem.useImaginary = False
problem.params = [3.0, 0.0, 0.0, 0.0]
problem.bulkIn = [0.0]
problem.bulkOut = [6.35e-06]
problem.qzshifts = []
problem.scalefactors = [0.23]
problem.domainRatio = []
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastQzshifts = []
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [1]
problem.contrastBackgroundActions = [1]
problem.contrastResolutionParams = [1]
problem.contrastCustomFiles = [float("NaN")]
problem.contrastDomainRatios = [0]
problem.resample = [False]
problem.dataPresent = [1]
problem.oilChiDataPresent = [0]
problem.numberOfContrasts = 1
problem.numberOfLayers = 1
problem.numberOfDomainContrasts = 0
problem.fitParams = [3.0]
problem.otherParams = [0.0, 0.0, 0.0, 1e-06, 0.23, 0.0, 6.35e-06, 0.03]
problem.fitLimits = [[1.0, 5.0]]
problem.otherLimits = [
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[1e-07, 1e-05],
[0.02, 0.25],
[0.0, 0.0],
[6.2e-06, 6.35e-06],
[0.01, 0.05],
]
return problem
@pytest.fixture
def domains_problem():
"""The expected problem object from "standard_layers_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.bulkIn = [0.0]
problem.bulkOut = [6.35e-06]
problem.qzshifts = []
problem.scalefactors = [0.23]
problem.domainRatio = [0.5]
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastQzshifts = []
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [1]
problem.contrastBackgroundActions = [1]
problem.contrastResolutionParams = [1]
problem.contrastCustomFiles = [float("NaN")]
problem.contrastDomainRatios = [1]
problem.resample = [False]
problem.dataPresent = [1]
problem.oilChiDataPresent = [0]
problem.numberOfContrasts = 1
problem.numberOfLayers = 1
problem.numberOfDomainContrasts = 2
problem.fitParams = [3.0]
problem.otherParams = [0.0, 0.0, 0.0, 1e-06, 0.23, 0.0, 6.35e-06, 0.03, 0.5]
problem.fitLimits = [[1.0, 5.0]]
problem.otherLimits = [
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[1e-07, 1e-05],
[0.02, 0.25],
[0.0, 0.0],
[6.2e-06, 6.35e-06],
[0.01, 0.05],
[0.4, 0.6],
]
return problem
@pytest.fixture
def custom_xy_problem():
"""The expected problem object from "custom_xy_project"."""
problem = ProblemDefinition()
problem.TF = Calculations.NonPolarised
problem.modelType = LayerModels.CustomXY
problem.geometry = Geometries.AirSubstrate
problem.useImaginary = False
problem.params = [3.0, 0.0, 0.0, 0.0]
problem.bulkIn = [0.0]
problem.bulkOut = [6.35e-06]
problem.qzshifts = []
problem.scalefactors = [0.23]
problem.domainRatio = []
problem.backgroundParams = [1e-06]
problem.resolutionParams = [0.03]
problem.contrastBulkIns = [1]
problem.contrastBulkOuts = [1]
problem.contrastQzshifts = []
problem.contrastScalefactors = [1]
problem.contrastBackgroundParams = [1]
problem.contrastBackgroundActions = [1]
problem.contrastResolutionParams = [1]
problem.contrastCustomFiles = [1]
problem.contrastDomainRatios = [0]
problem.resample = [False]
problem.dataPresent = [0]
problem.oilChiDataPresent = [0]
problem.numberOfContrasts = 1
problem.numberOfLayers = 0
problem.numberOfDomainContrasts = 0
problem.fitParams = [3.0]
problem.otherParams = [0.0, 0.0, 0.0, 1e-06, 0.23, 0.0, 6.35e-06, 0.03]
problem.fitLimits = [[1.0, 5.0]]
problem.otherLimits = [
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[1e-07, 1e-05],
[0.02, 0.25],
[0.0, 0.0],
[6.2e-06, 6.35e-06],
[0.01, 0.05],
]
return problem
@pytest.fixture
def standard_layers_cells():
"""The expected cells object from "standard_layers_project"."""
cells = Cells()
cells.f1 = [[0, 1]]
cells.f2 = [np.array([[1.0, 1.0, 1.0]])]
cells.f3 = [[1.0, 1.0]]
cells.f4 = [[1.0, 1.0]]
cells.f5 = [[1]]
cells.f6 = [[2, 3, 4, float("nan"), 2]]
cells.f7 = ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"]
cells.f8 = ["Background Param 1"]
cells.f9 = ["Scalefactor 1"]
cells.f10 = []
cells.f11 = ["SLD Air"]
cells.f12 = ["SLD D2O"]
cells.f13 = ["Resolution Param 1"]
cells.f14 = [dummy_function]
cells.f15 = [TypeOptions.Constant]
cells.f16 = [TypeOptions.Constant]
cells.f17 = [[[]]]
cells.f18 = []
cells.f19 = []
cells.f20 = []
cells.f21 = ["D2O"]
return cells
@pytest.fixture
def domains_cells():
"""The expected cells object from "domains_project"."""
cells = Cells()
cells.f1 = [[0, 1]]
cells.f2 = [np.array([[1.0, 1.0, 1.0]])]
cells.f3 = [[1.0, 1.0]]
cells.f4 = [[1.0, 1.0]]
cells.f5 = [[2, 1]]
cells.f6 = [[2, 3, 4, float("nan"), 2]]
cells.f7 = ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"]
cells.f8 = ["Background Param 1"]
cells.f9 = ["Scalefactor 1"]
cells.f10 = []
cells.f11 = ["SLD Air"]
cells.f12 = ["SLD D2O"]
cells.f13 = ["Resolution Param 1"]
cells.f14 = [dummy_function]
cells.f15 = [TypeOptions.Constant]
cells.f16 = [TypeOptions.Constant]
cells.f17 = [[[]]]
cells.f18 = [[0, 1], [0, 1]]
cells.f19 = [[1], [1]]
cells.f20 = ["Domain Ratio 1"]
cells.f21 = ["D2O"]
return cells
@pytest.fixture
def custom_xy_cells():
"""The expected cells object from "custom_xy_project"."""
cells = Cells()
cells.f1 = [[0, 1]]
cells.f2 = [np.empty([0, 3])]
cells.f3 = [[0.0, 0.0]]
cells.f4 = [[0.005, 0.7]]
cells.f5 = [[0]]
cells.f6 = [[0]]
cells.f7 = ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"]
cells.f8 = ["Background Param 1"]
cells.f9 = ["Scalefactor 1"]
cells.f10 = []
cells.f11 = ["SLD Air"]
cells.f12 = ["SLD D2O"]
cells.f13 = ["Resolution Param 1"]
cells.f14 = [dummy_function]
cells.f15 = [TypeOptions.Constant]
cells.f16 = [TypeOptions.Constant]
cells.f17 = [[[]]]
cells.f18 = []
cells.f19 = []
cells.f20 = []
cells.f21 = ["D2O"]
return cells
@pytest.fixture
def non_polarised_limits():
"""The expected limits object from "standard_layers_project" and "custom_xy_project"."""
limits = Limits()
limits.param = [[1.0, 5.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
limits.backgroundParam = [[1e-7, 1e-5]]
limits.qzshift = []
limits.scalefactor = [[0.02, 0.25]]
limits.bulkIn = [[0.0, 0.0]]
limits.bulkOut = [[6.2e-6, 6.35e-6]]
limits.resolutionParam = [[0.01, 0.05]]
limits.domainRatio = []
return limits
@pytest.fixture
def domains_limits():
"""The expected limits object from "domains_project"."""
limits = Limits()
limits.param = [[1.0, 5.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
limits.backgroundParam = [[1e-7, 1e-5]]
limits.qzshift = []
limits.scalefactor = [[0.02, 0.25]]
limits.bulkIn = [[0.0, 0.0]]
limits.bulkOut = [[6.2e-6, 6.35e-6]]
limits.resolutionParam = [[0.01, 0.05]]
limits.domainRatio = [[0.4, 0.6]]
return limits
@pytest.fixture
def non_polarised_priors():
"""The expected priors object from "standard_layers_project" and "custom_xy_project"."""
priors = Priors()
priors.param = [
["Substrate Roughness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test Thickness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test SLD", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test Roughness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
]
priors.backgroundParam = [["Background Param 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.qzshift = []
priors.scalefactor = [["Scalefactor 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.bulkIn = [["SLD Air", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.bulkOut = [["SLD D2O", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.resolutionParam = [["Resolution Param 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.domainRatio = []
priors.priorNames = [
"Substrate Roughness",
"Test Thickness",
"Test SLD",
"Test Roughness",
"Background Param 1",
"Scalefactor 1",
"SLD Air",
"SLD D2O",
"Resolution Param 1",
]
priors.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],
]
return priors
@pytest.fixture
def domains_priors():
"""The expected priors object from "domains_project"."""
priors = Priors()
priors.param = [
["Substrate Roughness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test Thickness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test SLD", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
["Test Roughness", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf],
]
priors.backgroundParam = [["Background Param 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.qzshift = []
priors.scalefactor = [["Scalefactor 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.bulkIn = [["SLD Air", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.bulkOut = [["SLD D2O", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.resolutionParam = [["Resolution Param 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.domainRatio = [["Domain Ratio 1", RATapi.utils.enums.Priors.Uniform, 0.0, np.inf]]
priors.priorNames = [
"Substrate Roughness",
"Test Thickness",
"Test SLD",
"Test Roughness",
"Background Param 1",
"Scalefactor 1",
"SLD Air",
"SLD D2O",
"Resolution Param 1",
"Domain Ratio 1",
]
priors.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],
]
return priors
@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.calcSldDuringFit = False
controls.resampleParams = [0.9, 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
controls.checks.fitParam = [1, 0, 0, 0]
controls.checks.fitBackgroundParam = [0]
controls.checks.fitQzshift = []
controls.checks.fitScalefactor = [0]
controls.checks.fitBulkIn = [0]
controls.checks.fitBulkOut = [0]
controls.checks.fitResolutionParam = [0]
controls.checks.fitDomainRatio = []
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.calcSldDuringFit = True
controls.resampleParams = [0.9, 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
controls.checks.fitParam = [1, 0, 0, 0]
controls.checks.fitBackgroundParam = [0]
controls.checks.fitQzshift = []
controls.checks.fitScalefactor = [0]
controls.checks.fitBulkIn = [0]
controls.checks.fitBulkOut = [0]
controls.checks.fitResolutionParam = [0]
controls.checks.fitDomainRatio = []
return controls
@pytest.fixture
def test_checks():
"""The expected checks object from "standard_layers_project", "domains_project" and "custom_xy_project"."""
checks = Checks()
checks.fitParam = [1, 0, 0, 0]
checks.fitBackgroundParam = [0]
checks.fitQzshift = []
checks.fitScalefactor = [0]
checks.fitBulkIn = [0]
checks.fitBulkOut = [0]
checks.fitResolutionParam = [0]
checks.fitDomainRatio = []
return checks
@pytest.mark.parametrize(
["test_project", "test_problem", "test_cells", "test_limits", "test_priors", "test_controls"],
[
(
"standard_layers_project",
"standard_layers_problem",
"standard_layers_cells",
"non_polarised_limits",
"non_polarised_priors",
"standard_layers_controls",
),
(
"custom_xy_project",
"custom_xy_problem",
"custom_xy_cells",
"non_polarised_limits",
"non_polarised_priors",
"custom_xy_controls",
),
(
"domains_project",
"domains_problem",
"domains_cells",
"domains_limits",
"domains_priors",
"standard_layers_controls",
),
],
)
def test_make_input(test_project, test_problem, test_cells, test_limits, test_priors, test_controls, request) -> None:
"""When converting the "project" and "controls", we should obtain the five input objects required for the compiled
RAT code.
"""
test_project = request.getfixturevalue(test_project)
test_problem = request.getfixturevalue(test_problem)
test_cells = request.getfixturevalue(test_cells)
test_limits = request.getfixturevalue(test_limits)
test_priors = request.getfixturevalue(test_priors)
test_controls = request.getfixturevalue(test_controls)
parameter_fields = [
"param",
"backgroundParam",
"scalefactor",
"qzshift",
"bulkIn",
"bulkOut",
"resolutionParam",
"domainRatio",
]
mocked_matlab_future = mock.MagicMock()
mocked_engine = mock.MagicMock()
mocked_matlab_future.result.return_value = mocked_engine
with mock.patch.object(
RATapi.wrappers.MatlabWrapper,
"loader",
mocked_matlab_future,
), mock.patch.object(RATapi.rat_core, "DylibEngine", mock.MagicMock()), mock.patch.object(
RATapi.inputs,
"get_python_handle",
mock.MagicMock(return_value=dummy_function),
), mock.patch.object(
RATapi.wrappers.MatlabWrapper,
"getHandle",
mock.MagicMock(return_value=dummy_function),
), mock.patch.object(RATapi.wrappers.DylibWrapper, "getHandle", mock.MagicMock(return_value=dummy_function)):
problem, cells, limits, priors, controls = make_input(test_project, RATapi.Controls())
problem = pickle.loads(pickle.dumps(problem))
check_problem_equal(problem, test_problem)
cells = pickle.loads(pickle.dumps(cells))
check_cells_equal(cells, test_cells)
limits = pickle.loads(pickle.dumps(limits))
for limit_field in parameter_fields:
assert (getattr(limits, limit_field) == getattr(test_limits, limit_field)).all()
priors = pickle.loads(pickle.dumps(priors))
for prior_field in parameter_fields:
assert getattr(priors, prior_field) == getattr(test_priors, prior_field)
assert priors.priorNames == test_priors.priorNames
assert (priors.priorValues == test_priors.priorValues).all()
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",
],
)
def test_check_indices(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(
["test_problem", "index_list", "bad_value"],
[
("standard_layers_problem", "contrastBulkIns", [0.0]),
("standard_layers_problem", "contrastBulkIns", [2.0]),
("standard_layers_problem", "contrastBulkOuts", [0.0]),
("standard_layers_problem", "contrastBulkOuts", [2.0]),
("standard_layers_problem", "contrastScalefactors", [0.0]),
("standard_layers_problem", "contrastScalefactors", [2.0]),
("standard_layers_problem", "contrastBackgroundParams", [0.0]),
("standard_layers_problem", "contrastBackgroundParams", [2.0]),
("standard_layers_problem", "contrastResolutionParams", [0.0]),
("standard_layers_problem", "contrastResolutionParams", [2.0]),
("custom_xy_problem", "contrastBulkIns", [0.0]),
("custom_xy_problem", "contrastBulkIns", [2.0]),
("custom_xy_problem", "contrastBulkOuts", [0.0]),
("custom_xy_problem", "contrastBulkOuts", [2.0]),
("custom_xy_problem", "contrastScalefactors", [0.0]),
("custom_xy_problem", "contrastScalefactors", [2.0]),
("custom_xy_problem", "contrastBackgroundParams", [0.0]),
("custom_xy_problem", "contrastBackgroundParams", [2.0]),
("custom_xy_problem", "contrastResolutionParams", [0.0]),
("custom_xy_problem", "contrastResolutionParams", [2.0]),
("domains_problem", "contrastBulkIns", [0.0]),
("domains_problem", "contrastBulkIns", [2.0]),
("domains_problem", "contrastBulkOuts", [0.0]),
("domains_problem", "contrastBulkOuts", [2.0]),
("domains_problem", "contrastScalefactors", [0.0]),
("domains_problem", "contrastScalefactors", [2.0]),
("domains_problem", "contrastDomainRatios", [0.0]),
("domains_problem", "contrastDomainRatios", [2.0]),
("domains_problem", "contrastBackgroundParams", [0.0]),
("domains_problem", "contrastBackgroundParams", [2.0]),
("domains_problem", "contrastResolutionParams", [0.0]),
("domains_problem", "contrastResolutionParams", [2.0]),
],
)
def test_check_indices_error(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": "bulkIn",
"contrastBulkOuts": "bulkOut",
"contrastScalefactors": "scalefactors",
"contrastDomainRatios": "domainRatio",
"contrastBackgroundParams": "backgroundParams",
"contrastResolutionParams": "resolutionParams",
}
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 lie '
f'outside of the range of "{param_list[index_list]}"',
):
check_indices(test_problem)
@pytest.mark.parametrize(
["test_project", "test_cells"],
[
("standard_layers_project", "standard_layers_cells"),
("custom_xy_project", "custom_xy_cells"),
("domains_project", "domains_cells"),
],
)
def test_make_cells(test_project, test_cells, request) -> None:
"""The cells object should be populated according to the input project object."""
test_project = request.getfixturevalue(test_project)
test_cells = request.getfixturevalue(test_cells)
mocked_matlab_future = mock.MagicMock()
mocked_engine = mock.MagicMock()
mocked_matlab_future.result.return_value = mocked_engine
with mock.patch.object(
RATapi.wrappers.MatlabWrapper,
"loader",
mocked_matlab_future,
), mock.patch.object(RATapi.rat_core, "DylibEngine", mock.MagicMock()), mock.patch.object(
RATapi.inputs,
"get_python_handle",
mock.MagicMock(return_value=dummy_function),
), mock.patch.object(
RATapi.wrappers.MatlabWrapper,
"getHandle",
mock.MagicMock(return_value=dummy_function),
), mock.patch.object(RATapi.wrappers.DylibWrapper, "getHandle", mock.MagicMock(return_value=dummy_function)):
cells = make_cells(test_project)
check_cells_equal(cells, test_cells)
def test_get_python_handle():
path = pathlib.Path(__file__).parent.resolve()
assert RATapi.inputs.get_python_handle("utils.py", "dummy_function", path).__code__ == dummy_function.__code__
def test_make_controls(standard_layers_controls, test_checks) -> 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(), test_checks)
check_controls_equal(controls, standard_layers_controls)
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",
]
array_fields = [
"params",
"backgroundParams",
"qzshifts",
"scalefactors",
"bulkIn",
"bulkOut",
"resolutionParams",
"domainRatio",
"contrastBackgroundParams",
"contrastBackgroundActions",
"contrastQzshifts",
"contrastScalefactors",
"contrastBulkIns",
"contrastBulkOuts",
"contrastResolutionParams",
"contrastDomainRatios",
"resample",
"dataPresent",
"oilChiDataPresent",
"fitParams",
"otherParams",
"fitLimits",
"otherLimits",
]
for scalar_field in scalar_fields:
assert getattr(actual_problem, scalar_field) == getattr(expected_problem, scalar_field)
for array_field in array_fields:
assert (getattr(actual_problem, array_field) == getattr(expected_problem, array_field)).all()
# Need to account for "NaN" entries in contrastCustomFiles field
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_cells_equal(actual_cells, expected_cells) -> None:
"""Compare two instances of the "cells" object for equality."""
assert actual_cells.f1 == expected_cells.f1
# Need to test equality of the numpy arrays separately
for a, b in zip(actual_cells.f2, expected_cells.f2):
assert (a == b).all()
# f6 may contain "NaN" values, so consider separately
assert actual_cells.f6 == expected_cells.f6 or [
"NaN" if np.isnan(el) else el for entry in actual_cells.f6 for el in entry
] == ["NaN" if np.isnan(el) else el for entry in expected_cells.f6 for el in entry]
for index in chain(range(3, 6), range(7, 21)):
field = f"f{index}"
assert getattr(actual_cells, field) == getattr(expected_cells, field)
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",
"calcSldDuringFit",
"display",
"xTolerance",
"funcTolerance",
"maxFuncEvals",
"maxIterations",
"updateFreq",
"updatePlotFreq",
"populationSize",
"fWeight",
"crossoverProbability",
"strategy",
"targetValue",
"numGenerations",
"nLive",
"nMCMC",
"propScale",
"nsTolerance",
"nSamples",
"nChains",
"jumpProbability",
"pUnitGamma",
"boundHandling",
"adaptPCR",
]
checks_fields = [
"fitParam",
"fitBackgroundParam",
"fitQzshift",
"fitScalefactor",
"fitBulkIn",
"fitBulkOut",
"fitResolutionParam",
"fitDomainRatio",
]
# Check "resampleParams" separately as it is an array
assert (actual_controls.resampleParams == expected_controls.resampleParams).all()
for field in controls_fields:
assert getattr(actual_controls, field) == getattr(expected_controls, field)
for field in checks_fields:
assert (getattr(actual_controls.checks, field) == getattr(expected_controls.checks, field)).all()