1
|
|
|
# This is temporary fix to import module from parent folder |
2
|
|
|
# It will be removed when package is published on PyPI |
3
|
|
|
import sys |
4
|
|
|
sys.path.append('../') |
5
|
|
|
# End of fix |
6
|
|
|
|
7
|
|
|
import random |
8
|
|
|
import logging |
9
|
|
|
from NiaPy.algorithms.basic import BatAlgorithm |
10
|
|
|
from NiaPy.benchmarks import Griewank |
11
|
|
|
|
12
|
|
|
logging.basicConfig() |
13
|
|
|
logger = logging.getLogger('examples') |
14
|
|
|
logger.setLevel('INFO') |
15
|
|
|
|
16
|
|
|
# For reproducive results |
17
|
|
|
random.seed(1234) |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
class MyBenchmark(object): |
21
|
|
|
def __init__(self): |
22
|
|
|
self.Lower = -11 |
23
|
|
|
self.Upper = 11 |
24
|
|
|
|
25
|
|
|
def function(self): |
26
|
|
|
def evaluate(D, sol): |
27
|
|
|
val = 0.0 |
28
|
|
|
for i in range(D): |
29
|
|
|
val = val + sol[i] * sol[i] |
30
|
|
|
return val |
31
|
|
|
return evaluate |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
# example using custom benchmark "MyBenchmark" |
35
|
|
|
logger.info('Running with custom MyBenchmark...') |
36
|
|
|
for i in range(10): |
37
|
|
|
Algorithm = BatAlgorithm(10, 40, 10000, 0.5, 0.5, 0.0, 2.0, MyBenchmark()) |
38
|
|
|
Best = Algorithm.run() |
39
|
|
|
|
40
|
|
|
logger.info(Best) |
41
|
|
|
|
42
|
|
|
# example using predifined benchmark function |
43
|
|
|
# available benchmarks are: |
44
|
|
|
# - griewank |
45
|
|
|
# - rastrigin |
46
|
|
|
# - rosenbrock |
47
|
|
|
# - sphere |
48
|
|
|
logger.info('Running with default Griewank benchmark...') |
49
|
|
|
|
50
|
|
|
griewank = Griewank() |
51
|
|
|
|
52
|
|
|
for i in range(10): |
53
|
|
|
Algorithm = BatAlgorithm(10, 40, 10000, 0.5, 0.5, 0.0, 2.0, griewank) |
54
|
|
|
Best = Algorithm.run() |
55
|
|
|
|
56
|
|
|
logger.info(Best) |
57
|
|
|
|
58
|
|
|
logger.info( |
59
|
|
|
'Running with default Griewank benchmark - should be the same as previous implementataion...') |
60
|
|
|
|
61
|
|
|
for i in range(10): |
62
|
|
|
Algorithm = BatAlgorithm(10, 40, 10000, 0.5, 0.5, 0.0, 2.0, 'griewank') |
63
|
|
|
Best = Algorithm.run() |
64
|
|
|
|
65
|
|
|
logger.info(Best) |
66
|
|
|
|
67
|
|
|
# example with changed griewank's lower and upper bounds |
68
|
|
|
logger.info('Running with Griewank with changed Upper and Lower bounds...') |
69
|
|
|
|
70
|
|
|
griewank = Griewank(-50, 50) |
71
|
|
|
|
72
|
|
|
for i in range(10): |
73
|
|
|
Algorithm = BatAlgorithm(10, 40, 10000, 0.5, 0.5, 0.0, 2.0, griewank) |
74
|
|
|
Best = Algorithm.run() |
75
|
|
|
|
76
|
|
|
logger.info(Best) |
77
|
|
|
|