tests.test_callbacks.test_callback_2()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 20
rs 9.7
c 0
b 0
f 0
cc 1
nop 0
1
"""Test module for callback functionality."""
2
3
import numpy as np
4
5
from hyperactive import Hyperactive
6
7
search_space = {
8
    "x1": list(np.arange(-100, 100, 1)),
9
}
10
11
12
def test_callback_0():
13
    """Test callbacks executed before objective function."""
14
15
    def callback_1(access):
16
        access.stuff1 = 1
17
18
    def callback_2(access):
19
        access.stuff2 = 2
20
21
    def objective_function(access):
22
        assert access.stuff1 == 1
23
        assert access.stuff2 == 2
24
25
        return 0
26
27
    hyper = Hyperactive()
28
    hyper.add_search(
29
        objective_function,
30
        search_space,
31
        n_iter=100,
32
        callbacks={"before": [callback_1, callback_2]},
33
    )
34
    hyper.run()
35
36
37
def test_callback_1():
38
    """Test callbacks executed before and after objective function."""
39
40
    def callback_1(access):
41
        access.stuff1 = 1
42
43
    def callback_2(access):
44
        access.stuff1 = 2
45
46
    def objective_function(access):
47
        assert access.stuff1 == 1
48
49
        return 0
50
51
    hyper = Hyperactive()
52
    hyper.add_search(
53
        objective_function,
54
        search_space,
55
        n_iter=100,
56
        callbacks={"before": [callback_1], "after": [callback_2]},
57
    )
58
    hyper.run()
59
60
61
def test_callback_2():
62
    """Test callbacks with pass_through parameter."""
63
64
    def callback_1(access):
65
        access.pass_through["stuff1"] = 1
66
67
    def objective_function(access):
68
        assert access.pass_through["stuff1"] == 1
69
70
        return 0
71
72
    hyper = Hyperactive()
73
    hyper.add_search(
74
        objective_function,
75
        search_space,
76
        n_iter=100,
77
        callbacks={"before": [callback_1]},
78
        pass_through={"stuff1": 0},
79
    )
80
    hyper.run()
81
82
83
def test_callback_3():
84
    """Test callbacks executed after objective function with pass_through."""
85
86
    def callback_1(access):
87
        access.pass_through["stuff1"] = 1
88
89
    def objective_function(access):
90
        if access.nth_iter == 0:
91
            assert access.pass_through["stuff1"] == 0
92
        else:
93
            assert access.pass_through["stuff1"] == 1
94
95
        return 0
96
97
    hyper = Hyperactive()
98
    hyper.add_search(
99
        objective_function,
100
        search_space,
101
        n_iter=100,
102
        callbacks={"after": [callback_1]},
103
        pass_through={"stuff1": 0},
104
    )
105
    hyper.run()
106