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

advanced_example_custom_pop   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 23.26 %

Importance

Changes 0
Metric Value
eloc 26
dl 10
loc 43
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A MyBenchmark.__init__() 2 2 1
A MyBenchmark.function() 6 6 2

1 Function

Rating   Name   Duplication   Size   Complexity  
A MyInit() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

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
# 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