| Total Complexity | 4 |
| Total Lines | 43 |
| Duplicated Lines | 23.26 % |
| 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 | # 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): |
|
|
|
|||
| 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 |