Beispiel #1
0
 def setUp(self):
     self.dimension = 20
     rng = default_rng()
     self.x = rng.uniform(-100, 100, self.dimension)
     self.task = Task(max_evals=230, max_iters=np.inf, problem=MyProblem(self.dimension))
     self.s1 = Individual(x=self.x, e=False)
     self.s2 = Individual(task=self.task, rng=rng)
     self.s3 = Individual(task=self.task)
Beispiel #2
0
 def setUp(self):
     self.D, self.nFES, self.nGEN = 10, 10, 10
     self.Lower, self.Upper = [2, 1, 1], [10, 10, 5]
     self.task = Task(dimension=self.D,
                      lower=self.Lower,
                      upper=self.Upper,
                      problem='sphere',
                      max_evals=self.nFES,
                      max_iters=self.nGEN,
                      cutoff_value=0.0)
Beispiel #3
0
class IndividualTestCase(TestCase):
    r"""Test case for testing Individual class.

    Date:
        April 2019

    Author:
        Klemen Berkovič

    See Also:
        * :class:`niapy.algorithms.Individual`

    """
    def setUp(self):
        self.dimension = 20
        rng = default_rng()
        self.x = rng.uniform(-100, 100, self.dimension)
        self.task = Task(max_evals=230,
                         max_iters=np.inf,
                         problem=MyProblem(self.dimension))
        self.s1 = Individual(x=self.x, e=False)
        self.s2 = Individual(task=self.task, rng=rng)
        self.s3 = Individual(task=self.task)

    def test_generate_solution(self):
        self.assertTrue(self.task.is_feasible(self.s2))
        self.assertTrue(self.task.is_feasible(self.s3))

    def test_evaluate(self):
        self.s1.evaluate(self.task)
        self.assertAlmostEqual(self.s1.f, self.task.eval(self.x))

    def test_repair(self):
        s = Individual(x=np.full(self.dimension, 100))
        self.assertFalse(self.task.is_feasible(s.x))

    def test_eq(self):
        self.assertFalse(self.s1 == self.s2)
        self.assertTrue(self.s1 == self.s1)
        s = Individual(x=self.s1.x)
        self.assertTrue(s == self.s1)

    def test_str(self):
        self.assertEqual(str(self.s1), '%s -> %s' % (self.x, np.inf))

    def test_getitem(self):
        for i in range(self.dimension):
            self.assertEqual(self.s1[i], self.x[i])

    def test_len(self):
        self.assertEqual(len(self.s1), len(self.x))
Beispiel #4
0
 def test_init_population_individual(self):
     r"""Test if custom generation initialization works ok."""
     a = Algorithm(population_size=10, initialization_function=init_pop_individual, individual_type=Individual)
     t = Task(problem=MyProblem(dimension=20))
     i = Individual(x=np.zeros(t.dimension), task=t)
     pop, fpop, d = a.init_population(t)
     for e in pop:
         self.assertEqual(i, e)
Beispiel #5
0
 def setUp(self):
     self.D, self.F, self.CR = 10, 0.9, 0.3
     self.x, self.task = default_rng().uniform(
         10, 50, self.D), Task(problem=MyProblem(self.D))
     self.s1, self.s2 = SolutionJDE(task=self.task, e=False), SolutionJDE(
         differential_weight=self.F,
         crossover_probability=self.CR,
         x=self.x)
Beispiel #6
0
 def test_init_population_numpy(self):
     r"""Test if custom generation initialization works ok."""
     a = Algorithm(population_size=10,
                   initialization_function=init_pop_numpy)
     t = Task(problem=MyProblem(dimension=20))
     self.assertTrue(
         np.array_equal(np.zeros((10, t.dimension)),
                        a.init_population(t)[0]))
Beispiel #7
0
    def task_factory(self, name):
        r"""Create optimization task.

        Args:
            name (str): Problem name.

        Returns:
            Task: Optimization task to use.

        """
        return Task(max_evals=self.max_evals,
                    dimension=self.dimension,
                    problem=name)
Beispiel #8
0
    def fit(self, x, y):
        r"""Fit NiaClass.

        Arguments:
            x (pandas.core.frame.DataFrame): n samples to classify.
            y (pandas.core.series.Series): n classes of the samples in the x array.

        Returns:
            None
        """
        feats = []

        for col in x:
            if is_numeric_dtype(x[col]):
                feats.append(_FeatureInfo(1, None, x[col].min(), x[col].max()))
            else:
                feats.append(_FeatureInfo(0, x[col].unique(), None, None))

        preprocessed_data = self.__preprocess_dataset(x, y, feats)

        algo = get_algorithm(self.__algo)
        algo.set_parameters(**self.__algo_args)

        problem = _NiaClassProblem(
            feats,
            y.unique(),
            x,
            y,
            preprocessed_data,
            self.__score_func_name,
            self.__classify,
        )
        task = Task(problem, max_evals=self.__num_evals)
        algo.run(task)

        self.__rules = problem.get_rules()
Beispiel #9
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import BacterialForagingOptimization
from niapy.task import Task
from niapy.problems import Griewank

# we will run Bacterial Foraging Optimization Algorithm for 5 independent runs
for i in range(5):
    task = Task(problem=Griewank(dimension=10, lower=-100.0, upper=100.0),
                max_iters=800,
                enable_logging=True)
    algo = BacterialForagingOptimization()
    best = algo.run(task)
    print('%s -> %s' % (best[0], best[1]))
Beispiel #10
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import ComprehensiveLearningParticleSwarmOptimizer
from niapy.problems import Sphere
from niapy.task import Task

# we will run ParticleSwarmAlgorithm for 5 independent runs
algo = ComprehensiveLearningParticleSwarmOptimizer(population_size=50,
                                                   c1=.3,
                                                   c2=1.0,
                                                   m=5,
                                                   w=0.86,
                                                   min_velocity=-2,
                                                   max_velocity=2)
for i in range(5):
    task = Task(problem=Sphere(dimension=25), max_evals=20000)
    best = algo.run(task=task)
    print('%s -> %f' % (best[0], best[1]))
print(algo.get_parameters())

# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
Beispiel #11
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import ParticleSwarmAlgorithm
from niapy.task import Task
from niapy.problems import Griewank

# we will run ParticleSwarmAlgorithm for 5 independent runs
algo = ParticleSwarmAlgorithm(population_size=100,
                              min_velocity=-4.0,
                              max_velocity=4.0)
for i in range(5):
    task = Task(problem=Griewank(dimension=10, lower=-600, upper=600),
                max_evals=10000)
    best = algo.run(task=task)
    print('%s -> %f' % (best[0], best[1]))
print(algo.get_parameters())

# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
Beispiel #12
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.problems import Sphere
from niapy.algorithms.basic import DynamicFireworksAlgorithm

# we will run Fireworks Algorithm for 5 independent runs
algo = DynamicFireworksAlgorithm(population_size=70,
                                 amplitude_init=0.1,
                                 amplitude_final=0.9)
for i in range(5):
    task = Task(problem=Sphere(dimension=10), max_iters=80)
    best = algo.run(task)
    print('%s -> %s' % (best[0], best[1]))
print(algo.get_parameters())

# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
Beispiel #13
0
 def test_BA_iters_to_fes(self):
     task = Task(max_iters=1000, problem=Sphere(10))
     algo = BatAlgorithm(population_size=10)
     algo.run_task(task)
     evals = task.evals
     self.assertEqual(10010, evals)
Beispiel #14
0
sys.path.append('../')

import numpy as np
from niapy.task import Task
from niapy.problems import Problem
from niapy.algorithms.basic import GreyWolfOptimizer


# our custom problem class
class MyProblem(Problem):
    def __init__(self, dimension, lower=-10, upper=10, *args, **kwargs):
        super().__init__(dimension, lower, upper, *args, **kwargs)

    def _evaluate(self, x):
        return np.sum(x ** 2)


# we will run 10 repetitions of Grey Wolf Optimizer against our custom MyProblem problem.
my_problem = MyProblem(20)
for i in range(10):
    task = Task(problem=my_problem, max_iters=100)

    # parameter is population size
    algo = GreyWolfOptimizer(population_size=20)

    # running algorithm returns best found minimum
    best = algo.run(task)

    # printing best minimum
    print(best[-1])
Beispiel #15
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.problems import Sphere
from niapy.algorithms.basic import CatSwarmOptimization

task = Task(problem=Sphere(dimension=10), max_evals=1000, enable_logging=True)
algo = CatSwarmOptimization()
best = algo.run(task=task)
print('%s -> %s' % (best[0], best[1]))
# plot a convergence graph
task.plot_convergence(x_axis='evals')
Beispiel #16
0
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')

import numpy as np
from niapy.task import Task
from niapy.problems import Problem
from niapy.algorithms.basic import ParticleSwarmAlgorithm


class MyProblem(Problem):
    def __init__(self, dimension, lower=-10, upper=10, *args, **kwargs):
        super().__init__(dimension, lower, upper, *args, **kwargs)

    def _evaluate(self, x):
        return np.sum(x**2)


# we will run Particle Swarm Algorithm on custom problem
task = Task(problem=MyProblem(dimension=10), max_iters=1000)
algo = ParticleSwarmAlgorithm(population_size=40,
                              c1=2.0,
                              c2=2.0,
                              w=0.7,
                              min_velocity=-4,
                              max_velocity=4)
best = algo.run(task=task)
print('%s -> %s ' % (best[0], best[1]))
Beispiel #17
0
 def test_FA_iters(self):
     task = Task(max_iters=1000, problem=Sphere(10))
     algo = FireflyAlgorithm(population_size=10)
     algo.run_task(task)
     iters = task.iters
     self.assertEqual(1000, iters)
Beispiel #18
0
 def test_FA_evals(self):
     task = Task(max_evals=1000, problem=Sphere(10))
     algo = FireflyAlgorithm(population_size=10)
     algo.run_task(task)
     evals = task.evals
     self.assertEqual(1000, evals)
Beispiel #19
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.problems import Sphere
from niapy.algorithms.basic import CatSwarmOptimization

task = Task(problem=Sphere(dimension=10), max_evals=1000, enable_logging=True)
algo = CatSwarmOptimization()
best = algo.run(task=task)
print('%s -> %s' % (best[0], best[1]))
# plot a convergence graph
task.plot()
Beispiel #20
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.algorithms.basic import DifferentialEvolution
from niapy.problems import Sphere

# 1 Number of function evaluations (nFES) as a stopping criteria
for i in range(10):
    task = Task(problem=Sphere(dimension=10), max_evals=10000)
    algo = DifferentialEvolution(population_size=40,
                                 crossover_probability=0.9,
                                 differential_weight=0.5)
    best = algo.run(task)
    print('%s -> %s' % (best[0], best[1]))

print('---------------------------------------')

# 2 Number of generations (iterations) as a stopping criteria
for i in range(10):
    task = Task(problem=Sphere(dimension=10), max_iters=1000)
    algo = DifferentialEvolution(population_size=40,
                                 crossover_probability=0.9,
                                 differential_weight=0.5)
    best = algo.run(task)
    print('%s -> %s' % (best[0], best[1]))
Beispiel #21
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.modified import SelfAdaptiveDifferentialEvolution
from niapy.task import Task
from niapy.problems import Griewank

# we will run jDE algorithm for 5 independent runs
algo = SelfAdaptiveDifferentialEvolution(f_lower=0.0,
                                         f_upper=2.0,
                                         tao1=0.9,
                                         tao2=0.45,
                                         population_size=40,
                                         differential_weight=0.5,
                                         crossover_probability=0.5)
for i in range(5):
    task = Task(problem=Griewank(dimension=10, lower=-600, upper=600),
                max_evals=10000,
                enable_logging=True)
    best = algo.run(task)
    print('%s -> %s' % (best[0], best[1]))
print(algo.get_parameters())
Beispiel #22
0
 def test_DE_iters(self):
     task = Task(max_iters=1000, problem=Sphere(10))
     algo = DifferentialEvolution(population_size=10, CR=0.9, F=0.5)
     algo.run_task(task)
     iters = task.iters
     self.assertEqual(1000, iters)
Beispiel #23
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.problems import Sphere
from niapy.algorithms.other import RandomSearch

task = Task(problem=Sphere(dimension=5), max_iters=5000)
algo = RandomSearch()
best = algo.run(task=task)
print(best)
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import GreyWolfOptimizer
from niapy.task import Task, OptimizationType
from niapy.problems import Pinter

# initialize Pinter problem with custom bound
pinter = Pinter(20, -5, 5)

# we will run 10 repetitions of Grey Wolf Optimizer against Pinter problem
for i in range(10):
    task = Task(problem=pinter, max_iters=100)

    # parameter is population size
    algo = GreyWolfOptimizer(population_size=20)

    # running algorithm returns best found minimum
    best = algo.run(task)

    # printing best minimum
    print(best[-1])
Beispiel #25
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import ParticleSwarmAlgorithm
from niapy.task import Task, OptimizationType
from niapy.problems import Sphere

# we will run ParticleSwarmAlgorithm for 5 independent runs
for i in range(5):
    task = Task(problem=Sphere(dimension=10),
                max_evals=10000,
                optimization_type=OptimizationType.MAXIMIZATION)
    algo = ParticleSwarmAlgorithm(population_size=40,
                                  c1=2.0,
                                  c2=2.0,
                                  w=0.7,
                                  min_velocity=-4,
                                  max_velocity=4)
    best = algo.run(task=task)
    print(best[-1])
Beispiel #26
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.task import Task
from niapy.problems import Sphere
from niapy.algorithms.basic import DifferentialEvolution

# Storing improvements during the evolutionary cycle

task = Task(max_evals=10000, problem=Sphere(dimension=10))
algo = DifferentialEvolution(population_size=40, crossover_probability=0.9, differential_weight=0.5)
best = algo.run(task)
evals, x_f = task.convergence_data(x_axis='evals')
print(evals)  # print function evaluations
print(x_f)  # print values
Beispiel #27
0
 def setUp(self):
     self.D = 20
     self.x, self.task = default_rng().uniform(-2, 2, self.D), Task(problem=MyProblem(self.D))
     self.sol1, self.sol2, self.sol3 = MkeSolution(x=self.x, e=False), MkeSolution(task=self.task), MkeSolution(
         x=self.x, e=False)
Beispiel #28
0
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import GreyWolfOptimizer
from niapy.task import Task

# we will run 10 repetitions of Grey Wolf Optimizer against Pinter problem
for i in range(10):
    task = Task(problem='pinter', dimension=10, max_evals=1000)
    algorithm = GreyWolfOptimizer(population_size=20)
    best = algorithm.run(task)
    print(best[-1])
Beispiel #29
0
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys

sys.path.append('../')
# End of fix

from niapy.algorithms.basic import EvolutionStrategyMp1
from niapy.task import Task
from niapy.problems import Sphere

# we will run Differential Evolution for 5 independent runs
for i in range(5):
    task = Task(problem=Sphere(dimension=10), max_evals=10000)
    algo = EvolutionStrategyMp1()
    best = algo.run(task)
    print('%s -> %f' % (best[0], best[1]))
Beispiel #30
0
class TaskTestCase(TestCase):
    r"""Test case for testing the Task class.

    Date:
        April 2019

    Author:
        Klemen Berkovič

    See Also:
        * :class:`niapy.util.Task`

    """
    def setUp(self):
        self.D, self.nFES, self.nGEN = 10, 10, 10
        self.Lower, self.Upper = [2, 1, 1], [10, 10, 5]
        self.task = Task(dimension=self.D,
                         lower=self.Lower,
                         upper=self.Upper,
                         problem='sphere',
                         max_evals=self.nFES,
                         max_iters=self.nGEN,
                         cutoff_value=0.0)

    def test_dim_ok(self):
        self.assertEqual(self.D, self.task.dimension)
        self.assertEqual(self.D, self.task.dimension)

    def test_lower(self):
        self.assertTrue(
            np.array_equal(full_array(self.Lower, self.D), self.task.lower))
        self.assertTrue(
            np.array_equal(full_array(self.Lower, self.D), self.task.lower))

    def test_upper(self):
        self.assertTrue(
            np.array_equal(full_array(self.Upper, self.D), self.task.upper))
        self.assertTrue(
            np.array_equal(full_array(self.Upper, self.D), self.task.upper))

    def test_range(self):
        self.assertTrue(
            np.array_equal(
                full_array(self.Upper, self.D) -
                full_array(self.Lower, self.D), self.task.range))
        self.assertTrue(
            np.array_equal(
                full_array(self.Upper, self.D) -
                full_array(self.Lower, self.D), self.task.range))

    def test_max_iters(self):
        self.assertEqual(self.nGEN, self.task.max_iters)

    def test_max_evals(self):
        self.assertEqual(self.nFES, self.task.max_evals)

    def test_is_feasible(self):
        x = np.full(self.D, 2)
        self.assertTrue(self.task.is_feasible(x))
        x = np.full(self.D, 3)
        self.assertTrue(self.task.is_feasible(x))
        x = default_rng().uniform(self.task.lower, self.task.upper, self.D)
        self.assertTrue(self.task.is_feasible(x))
        x = np.full(self.D, -20)
        self.assertFalse(self.task.is_feasible(x))
        x = np.full(self.D, 20)
        self.assertFalse(self.task.is_feasible(x))

    def test_next_iter(self):
        for i in range(self.nGEN):
            self.assertFalse(self.task.stopping_condition())
            self.task.next_iter()
        self.assertTrue(self.task.stopping_condition())

    def test_stop_cond_iter(self):
        for i in range(self.nGEN):
            self.assertFalse(self.task.stopping_condition_iter(),
                             msg='Error at %s iteration!!!' % i)
        self.assertTrue(self.task.stopping_condition_iter())

    def test_eval(self):
        x = np.ones(self.D)
        for i in range(self.nFES):
            self.assertAlmostEqual(self.task.eval(x),
                                   self.D,
                                   msg='Error at %s iteration!!!' % i)
        self.assertTrue(self.task.stopping_condition())

    def test_eval_over_max_evals(self):
        x = np.ones(self.D)
        for i in range(self.nFES):
            self.task.eval(x)
        self.assertEqual(np.inf, self.task.eval(x))
        self.assertTrue(self.task.stopping_condition())

    def test_eval_over_max_iters(self):
        x = np.ones(self.D)
        for i in range(self.nGEN):
            self.task.next_iter()
        self.assertEqual(np.inf, self.task.eval(x))
        self.assertTrue(self.task.stopping_condition())

    def test_evals_count(self):
        x = np.ones(self.D)
        for i in range(self.nFES):
            self.task.eval(x)
            self.assertEqual(self.task.evals, i + 1,
                             'Error at %s. evaluation' % (i + 1))

    def test_iters_count(self):
        for i in range(self.nGEN):
            self.task.next_iter()
            self.assertEqual(self.task.iters, i + 1,
                             'Error at %s. iteration' % (i + 1))

    def test_stop_cond_evals(self):
        x = np.ones(self.D)
        for i in range(self.nFES - 1):
            self.task.eval(x)
            self.assertFalse(self.task.stopping_condition())
        self.task.eval(x)
        self.assertTrue(self.task.stopping_condition())

    def test_stop_cond_iters(self):
        for i in range(self.nGEN - 1):
            self.task.next_iter()
            self.assertFalse(self.task.stopping_condition())
        self.task.next_iter()
        self.assertTrue(self.task.stopping_condition())

    def test_stop_cond_cutoff_value(self):
        x = np.ones(self.D)
        for i in range(self.nGEN - 5):
            self.assertFalse(self.task.stopping_condition())
            self.assertEqual(self.D, self.task.eval(x))
            self.task.next_iter()
        x = np.zeros(self.D)
        self.assertEqual(0, self.task.eval(x))
        self.assertTrue(self.task.stopping_condition())
        self.assertEqual(self.nGEN - 5, self.task.iters)

    def test_print_conv_one(self):
        r1, r2 = [], []
        for i in range(self.nFES):
            x = np.full(self.D, 10 - i)
            r1.append(i + 1), r2.append(self.task.eval(x))
        t_r1, t_r2 = self.task.return_conv()
        self.assertTrue(np.array_equal(r1, t_r1))
        self.assertTrue(np.array_equal(r2, t_r2))

    def test_print_conv_two(self):
        r1, r2 = [], []
        for i in range(self.nFES):
            x = np.full(self.D, 10 - i if i not in (3, 4, 5) else 4)
            r1.append(i + 1), r2.append(self.task.eval(x))
        t_r1, t_r2 = self.task.return_conv()
        self.assertTrue(np.array_equal(r2, t_r2))
        self.assertTrue(np.array_equal(r1, t_r1))