| Total Complexity | 2 |
| Total Lines | 54 |
| Duplicated Lines | 55.56 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | import pytest |
||
| 2 | from tqdm import tqdm |
||
| 3 | import numpy as np |
||
| 4 | |||
| 5 | from surfaces.test_functions.mathematical import RastriginFunction |
||
| 6 | |||
| 7 | from gradient_free_optimizers import ( |
||
| 8 | RandomSearchOptimizer, |
||
| 9 | RandomRestartHillClimbingOptimizer, |
||
| 10 | RandomAnnealingOptimizer, |
||
| 11 | ) |
||
| 12 | |||
| 13 | |||
| 14 | opt_global_l = ( |
||
| 15 | "Optimizer", |
||
| 16 | [ |
||
| 17 | (RandomSearchOptimizer), |
||
| 18 | (RandomRestartHillClimbingOptimizer), |
||
| 19 | (RandomAnnealingOptimizer), |
||
| 20 | ], |
||
| 21 | ) |
||
| 22 | |||
| 23 | |||
| 24 | View Code Duplication | @pytest.mark.parametrize(*opt_global_l) |
|
|
|
|||
| 25 | def test_global_perf(Optimizer): |
||
| 26 | ackley_function = RastriginFunction(n_dim=1, metric="score") |
||
| 27 | |||
| 28 | def objective_function(para): |
||
| 29 | score = -para["x1"] * para["x1"] |
||
| 30 | return score |
||
| 31 | |||
| 32 | search_space = {"x1": np.arange(-100, 101, 1)} |
||
| 33 | initialize = {"vertices": 2} |
||
| 34 | |||
| 35 | n_opts = 33 |
||
| 36 | n_iter = 100 |
||
| 37 | |||
| 38 | scores = [] |
||
| 39 | for rnd_st in tqdm(range(n_opts)): |
||
| 40 | opt = Optimizer(search_space, initialize=initialize, random_state=rnd_st) |
||
| 41 | opt.search( |
||
| 42 | objective_function, |
||
| 43 | n_iter=n_iter, |
||
| 44 | memory=False, |
||
| 45 | verbosity=False, |
||
| 46 | ) |
||
| 47 | |||
| 48 | scores.append(opt.best_score) |
||
| 49 | score_mean = np.array(scores).mean() |
||
| 50 | |||
| 51 | print("\n score_mean", score_mean) |
||
| 52 | |||
| 53 | assert score_mean > -5 |
||
| 54 |