class CSTestCase(TestCase): def setUp(self): self.pso_custom = ParticleSwarmAlgorithm(NP=40, D=40, nFES=1000, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark=MyBenchmark()) self.pso_griewank = ParticleSwarmAlgorithm(NP=40, D=40, nFES=1000, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark='griewank') def test_custom_works_fine(self): self.assertTrue(self.pso_custom.run()) def test_griewank_works_fine(self): self.assertTrue(self.pso_griewank.run())
def optimize(bench, algo): average_mfo = 0 average_de = 0 average_abc = 0 average_pso = 0 average_ba = 0 average_fa = 0 average_ga = 0 for i in np.arange(epoch): mfo = MothFlameOptimizer(D=dim, NP=pop, nGEN=maxIter, benchmark=bench) de = DifferentialEvolution(D=dim, NP=pop, nGEN=maxIter, benchmark=bench) abc = ArtificialBeeColonyAlgorithm(D=dim, NP=pop, nFES=maxIter, benchmark=bench) pso = ParticleSwarmAlgorithm(D=dim, NP=pop, nGEN=maxIter, benchmark=bench) ba = BatAlgorithm(D=dim, NP=pop, nFES=maxIter, benchmark=bench) fa = FireflyAlgorithm(D=dim, NP=pop, nFES=maxIter, benchmark=bench) ga = GeneticAlgorithm(D=dim, NP=pop, nFES=maxIter, benchmark=bench) gen, best_de = de.run() gen, best_mfo = mfo.run() gen, best_abc = abc.run() gen, best_pso = pso.run() gen, best_ba = ba.run() gen, best_fa = fa.run() gen, best_ga = ga.run() average_mfo += best_de / epoch average_de += best_mfo / epoch average_abc += best_abc / epoch average_pso += best_pso / epoch average_ba += best_ba / epoch average_fa += best_fa / epoch average_ga += best_ga / epoch print(algo, ': DE Average of Bests over', epoch, 'run: ', average_de) print(algo, ': MFO Average of Bests over', epoch, 'run: ', average_mfo) print(algo, ': ABC Average of Bests over', epoch, 'run: ', average_abc) print(algo, ': PSO Average of Bests over', epoch, 'run: ', average_pso) print(algo, ': BA Average of Bests over', epoch, 'run: ', average_ba) print(algo, ': FA Average of Bests over', epoch, 'run: ', average_fa) print(algo, ': GA Average of Bests over', epoch, 'run: ', average_ga) return [ average_de, average_mfo, average_abc, average_pso, average_ba, average_fa, average_ga ]
def plot_example(): task = TaskConvPlot(D=50, nFES=50000, nGEN=10000, benchmark=MyBenchmark()) algo = ParticleSwarmAlgorithm(NP=50, C1=2.0, C2=2.0, w=0.5, vMin=-5, vMax=5, task=task) best = algo.run() logger.info('%s %s' % (best[0], best[1])) input('Press [enter] to continue')
def logging_example(): task = TaskConvPrint(D=50, nFES=50000, nGEN=50000, benchmark=MyBenchmark()) algo = ParticleSwarmAlgorithm(NP=50, C1=2.0, C2=2.0, w=0.5, vMin=-5, vMax=5, seed=None, task=task) best = algo.run() logger.info('%s %s' % (best[0], best[1]))
class CSTestCase(TestCase): def setUp(self): self.pso_custom = ParticleSwarmAlgorithm(40, 40, 1000, 2.0, 2.0, 0.7, -4, 4, MyBenchmark()) self.pso_griewank = ParticleSwarmAlgorithm(40, 40, 1000, 2.0, 2.0, 0.7, -4, 4, 'griewank') def test_custom_works_fine(self): self.assertTrue(self.pso_custom.run()) def test_griewank_works_fine(self): self.assertTrue(self.pso_griewank.run())
def simple_example(runs=10): for i in range(10): algo = ParticleSwarmAlgorithm(NP=50, D=40, nFES=40000, C1=2.0, C2=2.0, w=0.5, vMin=-5, vMax=5, seed=i, benchmark=MyBenchmark()) Best = algo.run() logger.info('%s %s' % (Best[0], Best[1]))
def test_griewank_works_fine(self): pso_griewank = ParticleSwarmAlgorithm(NP=40, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, seed=self.seed) pso_griewankc = ParticleSwarmAlgorithm(NP=40, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, seed=self.seed) AlgorithmTestCase.algorithm_run_test(self, pso_griewank, pso_griewankc)
def test_custom_works_fine(self): wvcpso_custom = ParticleSwarmAlgorithm(NP=40, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, seed=self.seed) wvcpso_customc = ParticleSwarmAlgorithm(NP=40, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, seed=self.seed) AlgorithmTestCase.test_algorithm_run(self, wvcpso_custom, wvcpso_customc, MyBenchmark())
def setUp(self): self.pso_custom = ParticleSwarmAlgorithm(NP=40, D=40, nFES=1000, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark=MyBenchmark()) self.pso_griewank = ParticleSwarmAlgorithm(NP=40, D=40, nFES=1000, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark='griewank')
def executePSO(typeBenchmark): task = StoppingTask( D=dimensoes, nFES=numeroAvaliacoes, optType=tipoOtimizacao, benchmark=typeBenchmark, ) algo = ParticleSwarmAlgorithm( NP=tamanhoPopulacao, C1=componenteCognitivo, C2=componenteSocial, w=pesoInercial, vMin=velocidadeMinima, vMax=velocidadeMaxima, ) best = algo.run(task=task) return [task, best[1], best[0]]
def __init__(self, algorithm_name, objective, maxfeval, population=30): super().__init__(algorithm_name, objective, maxfeval) self.algorithm_name = algorithm_name self.algo = None #this is the suggest function from hyperopt if algorithm_name not in __all__: raise Exception('NiaPy does not have algorithm :' + str(algorithm_name)) elif self.algorithm_name == 'NiaPyABC': self.algo = ArtificialBeeColonyAlgorithm(NP=population, Limit=100) elif self.algorithm_name == 'NiaPyBat': self.algo = BatAlgorithm(NP=population) elif self.algorithm_name == 'NiaPyCuckooSearch': self.algo = CuckooSearch(N=population, pa=0.2, alpha=0.5) elif self.algorithm_name == 'NiaPyDifferentialEvolution': self.algo = DifferentialEvolution(NP=population, F=1, CR=0.8) elif self.algorithm_name == 'NiaPyFireflyAlgorithm': self.algo = FireflyAlgorithm(NP=population, alpha=0.5, betamin=0.2, gamma=1.0) elif self.algorithm_name == 'NiaPyGeneticAlgorithm': self.algo = FireflyAlgorithm(NP=population, Crossover=UniformCrossover, Mutation=UniformMutation, Cr=0.45, Mr=0.9) elif self.algorithm_name == 'NiaPyGWO': self.algo = GreyWolfOptimizer(NP=population) # config elif self.algorithm_name == 'NiaPyNelderMead': self.algo = NelderMeadMethod() # config elif self.algorithm_name == 'NiaPyPSO': self.algo = ParticleSwarmAlgorithm(NP=population, C1=2, C2=2, w=0.9, vMin=-1.5, vMax=1.5) # config # config # config elif self.algorithm_name == 'NiaPySimulatedAnnealing': self.algo = SimulatedAnnealing(coolingMethod=coolLinear)
def test_parameter_type(self): d = ParticleSwarmAlgorithm.typeParameters() self.assertTrue(d['C1'](10)) self.assertTrue(d['C2'](10)) self.assertTrue(d['C1'](0)) self.assertTrue(d['C2'](0)) self.assertFalse(d['C1'](-10)) self.assertFalse(d['C2'](-10)) self.assertTrue(d['vMax'](10)) self.assertTrue(d['vMin'](10)) self.assertTrue(d['NP'](10)) self.assertFalse(d['NP'](-10)) self.assertFalse(d['NP'](0)) self.assertFalse(d['vMin'](None)) self.assertFalse(d['vMax'](None))
# 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 import random from NiaPy.algorithms.basic import ParticleSwarmAlgorithm from NiaPy.task import StoppingTask, OptimizationType from NiaPy.benchmarks import Sphere #we will run ParticleSwarmAlgorithm for 5 independent runs for i in range(5): task = StoppingTask(D=10, nFES=1000, optType=OptimizationType.MAXIMIZATION, benchmark=Sphere()) algo = ParticleSwarmAlgorithm(NP=40, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4) best = algo.run(task=task) print best
def setUp(self): self.pso_custom = ParticleSwarmAlgorithm( 40, 40, 10000, 2.0, 2.0, 0.7, -4, 4, MyBenchmark()) self.pso_griewank = ParticleSwarmAlgorithm( 40, 40, 10000, 2.0, 2.0, 0.7, -4, 4, 'griewank')
def test_custom_works_fine(self): pso_custom = ParticleSwarmAlgorithm(NP=40, D=self.D, nFES=self.nFES, nGEN=self.nGEN, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark=MyBenchmark(), seed=self.seed) pso_customc = ParticleSwarmAlgorithm(NP=40, D=self.D, nFES=self.nFES, nGEN=self.nGEN, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark=MyBenchmark(), seed=self.seed) AlgorithmTestCase.algorithm_run_test(self, pso_custom, pso_customc)
def test_griewank_works_fine(self): pso_griewank = ParticleSwarmAlgorithm(NP=40, D=self.D, nFES=self.nFES, nGEN=self.nGEN, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark='griewank', seed=self.seed) pso_griewankc = ParticleSwarmAlgorithm(NP=40, D=self.D, nFES=self.nFES, nGEN=self.nGEN, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, benchmark='griewank', seed=self.seed) AlgorithmTestCase.algorithm_run_test(self, pso_griewank, pso_griewankc)
def test_algorithm_info(self): al = ParticleSwarmAlgorithm.algorithmInfo() self.assertIsNotNone(al)
# 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.task import StoppingTask, OptimizationType from NiaPy.benchmarks import Sphere from numpy import random as rand, apply_along_axis def MyInit(task, NP, rnd=rand, **kwargs): pop = 0.2 + rnd.rand(NP, task.D) * task.bRange fpop = apply_along_axis(task.eval, 1, pop) return pop, fpop # we will run Particle Swarm Algorithm with custom Init function for 5 independent runs for i in range(5): task = StoppingTask(D=10, nFES=1000, benchmark=Sphere()) algo = ParticleSwarmAlgorithm(NP=10, C1=2.0, C2=2.0, w=0.7, vMin=-4, vMax=4, InitPopFunc=MyInit) best = algo.run(task=task) print(best)
# encoding=utf8 # This is temporary fix to import module from parent folder # It will be removed when package is published on PyPI from NiaPy import Runner from NiaPy.algorithms.basic import (GreyWolfOptimizer, ParticleSwarmAlgorithm) from NiaPy.benchmarks import (Ackley, Griewank, Sphere, HappyCat) import sys sys.path.append('../') # End of fix """Example demonstrating the use of NiaPy Runner.""" runner = Runner( D=40, nFES=100, nRuns=1, useAlgorithms=[ GreyWolfOptimizer(), "FlowerPollinationAlgorithm", ParticleSwarmAlgorithm(), "HybridBatAlgorithm", "SimulatedAnnealing", "CuckooSearch" ], useBenchmarks=[Ackley(), Griewank(), Sphere(), HappyCat(), "rastrigin"]) print(runner.run(verbose=True))
Ackley, Griewank, Sphere, HappyCat ) """Example demonstrating the use of NiaPy Runner.""" runner = Runner( D=40, nFES=100, nRuns=2, useAlgorithms=[ GreyWolfOptimizer(), "FlowerPollinationAlgorithm", ParticleSwarmAlgorithm(), "HybridBatAlgorithm", "SimulatedAnnealing", "CuckooSearch"], useBenchmarks=[ Ackley(), Griewank(), Sphere(), HappyCat(), "rastrigin"] ) print(runner.run(verbose=True))
# 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 import random from NiaPy.algorithms.basic import ParticleSwarmAlgorithm for i in range(10): Algorithm = ParticleSwarmAlgorithm(50, 40, 40000, 2.0, 2.0, 0.5, -5, 5, 'sphere') Best = Algorithm.run() print(Best)
def __init__(self): Benchmark.__init__(self, -10, 10) def function(self): def evaluate(D, sol): val = 0.0 for i in range(D): val += sol[i]**2 return val return evaluate runner = Runner(D=40, nFES=100, nRuns=2, useAlgorithms=[ GreyWolfOptimizer(), "FlowerPollinationAlgorithm", ParticleSwarmAlgorithm(), "HybridBatAlgorithm", "SimulatedAnnealing", "CuckooSearch" ], useBenchmarks=[ Ackley(), Griewank(), Sphere(), HappyCat(), "rastrigin", MyBenchmark() ]) runner.run(export='json', verbose=True)
logging.basicConfig() logger = logging.getLogger('examples') logger.setLevel('INFO') # For reproducive results random.seed(1234) class MyBenchmark(object): def __init__(self): self.Lower = -11 self.Upper = 11 def function(self): def evaluate(D, sol): val = 0.0 for i in range(D): val = val + sol[i] * sol[i] return val return evaluate for i in range(10): Algorithm = ParticleSwarmAlgorithm(50, 40, 40000, 2.0, 2.0, 0.5, -5, 5, MyBenchmark()) Best = Algorithm.run() logger.info(Best)
# 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 import random from NiaPy.algorithms.basic import ParticleSwarmAlgorithm from NiaPy.task import StoppingTask from NiaPy.benchmarks import Griewank # we will run ParticleSwarmAlgorithm for 5 independent runs algo = ParticleSwarmAlgorithm(NP=100, vMin=-4.0, vMax=4.0) for i in range(5): task = StoppingTask(D=10, nFES=10000, benchmark=Griewank(Lower=-600, Upper=600)) best = algo.run(task=task) print('%s -> %f' % (best[0], best[1])) print(algo.getParameters()) # vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
# 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 import random from NiaPy.algorithms.basic import ParticleSwarmAlgorithm def Fun(D, sol): val = 0.0 for i in range(D): val = val + sol[i] * sol[i] return val for i in range(10): Algorithm = ParticleSwarmAlgorithm(40, 40, 10000, 2.0, 2.0, 0.7, -5.0, 5.0, Fun) Best = Algorithm.run() print(Best)