tests.test_max_score.objective_function()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
"""Test module for max score functionality."""
2
3
import time
4
5
import numpy as np
6
7
from hyperactive import Hyperactive
8
from hyperactive.optimizers import (
9
    HillClimbingOptimizer,
10
)
11
12
13
def objective_function(para):
14
    """Return simple quadratic objective function for testing."""
15
    score = -para["x1"] * para["x1"]
16
    return score
17
18
19
search_space = {
20
    "x1": list(np.arange(0, 100000, 0.1)),
21
}
22
23
24
def test_max_score_0():
25
    """Test max_score termination with hill climbing optimizer."""
26
27
    def objective_function(para):
28
        score = -para["x1"] * para["x1"]
29
        return score
30
31
    search_space = {
32
        "x1": list(np.arange(0, 100, 0.1)),
33
    }
34
35
    max_score = -9999
36
37
    opt = HillClimbingOptimizer(
38
        epsilon=0.01,
39
        rand_rest_p=0,
40
    )
41
42
    hyper = Hyperactive()
43
    hyper.add_search(
44
        objective_function,
45
        search_space,
46
        optimizer=opt,
47
        n_iter=100000,
48
        initialize={"warm_start": [{"x1": 99}]},
49
        max_score=max_score,
50
    )
51
    hyper.run()
52
53
    print("\n Results head \n", hyper.search_data(objective_function).head())
54
    print("\n Results tail \n", hyper.search_data(objective_function).tail())
55
56
    print("\nN iter:", len(hyper.search_data(objective_function)))
57
58
    assert -100 > hyper.best_score(objective_function) > max_score
59
60
61
def test_max_score_1():
62
    """Test max_score termination with time constraint."""
63
64
    def objective_function(para):
65
        score = -para["x1"] * para["x1"]
66
        time.sleep(0.01)
67
        return score
68
69
    search_space = {
70
        "x1": list(np.arange(0, 100, 0.1)),
71
    }
72
73
    max_score = -9999
74
75
    c_time = time.perf_counter()
76
    hyper = Hyperactive()
77
    hyper.add_search(
78
        objective_function,
79
        search_space,
80
        n_iter=100000,
81
        initialize={"warm_start": [{"x1": 99}]},
82
        max_score=max_score,
83
    )
84
    hyper.run()
85
    diff_time = time.perf_counter() - c_time
86
87
    print("\n Results head \n", hyper.search_data(objective_function).head())
88
    print("\n Results tail \n", hyper.search_data(objective_function).tail())
89
90
    print("\nN iter:", len(hyper.search_data(objective_function)))
91
92
    assert diff_time < 1
93