Completed
Push — master ( 9a7980...2248e9 )
by Grega
19s queued 14s
created

advanced_example_custom_pop.MyBenchmark.function()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 6

Duplication

Lines 6
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 1
dl 6
loc 6
rs 10
c 0
b 0
f 0
1
# encoding=utf8
2
# This is temporary fix to import module from parent folder
3
# It will be removed when package is published on PyPI
4
import sys
5
sys.path.append('../')
6
7
from NiaPy.task import StoppingTask, OptimizationType
8
from NiaPy.benchmarks import Benchmark
9
from NiaPy.algorithms.basic import GreyWolfOptimizer
10
from numpy import random as rand, apply_along_axis
11
12
# our custom benchmark class
13 View Code Duplication
class MyBenchmark(Benchmark):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
14
	def __init__(self):
15
		Benchmark.__init__(self, -10, 10)
16
17
	def function(self):
18
		def evaluate(D, sol):
19
			val = 0.0
20
			for i in range(D): val += sol[i] ** 2
21
			return val
22
		return evaluate
23
24
25
# custom initialization population function
26
def MyInit(task, NP, rnd=rand, **kwargs):
27
    pop = 0.2 + rnd.rand(NP, task.D) * task.bRange
28
    fpop = apply_along_axis(task.eval, 1, pop)
29
    return pop, fpop
30
31
# we will run 10 repetitions of Grey Wolf Optimizer against our custom MyBenchmark benchmark function
32
for i in range(10):
33
    task = StoppingTask(D=20, nGEN=100, optType=OptimizationType.MINIMIZATION, benchmark=MyBenchmark())
34
35
    # parameter is population size
36
    algo = GreyWolfOptimizer(NP=20, InitPopFunc=MyInit)
37
38
    # running algorithm returns best found minimum
39
    best = algo.run(task)
40
41
    # printing best minimum
42
    print(best[-1])
43