X-Git-Url: http://git.tomasm.cz/imago.git/blobdiff_plain/ecb0ef2b5ea477ee170ce083f59d2200af7117a2..24a7e923346be5e355a7d61e642fc469310444ef:/pso.py diff --git a/pso.py b/pso.py index 9fdee2d..6d6fada 100644 --- a/pso.py +++ b/pso.py @@ -4,9 +4,14 @@ import random import multiprocessing from functools import partial -def particle(dimension, bound, func_d): - position = [2 * bound * random.random() - bound for _ in xrange(dimension)] - velocity = [2 * bound * random.random() - bound for _ in xrange(dimension)] +import lhs + +def particle(dimension, bound, v_max, func_d, pos=None): + if not pos: + position = [2 * bound * random.random() - bound for _ in xrange(dimension)] + else: + position = pos + velocity = [2 * v_max * random.random() - v_max for _ in xrange(dimension)] value = func_d(*position) return value, position, velocity, value, position @@ -26,11 +31,13 @@ def move(particle, omega, phi_p, phi_g, v_max, global_best, func_d): def optimize(dimension, boundary, function_d, n_parts, n_turns): pool = multiprocessing.Pool(None) - particles = [particle(dimension, boundary, function_d) - for _ in xrange(n_parts)] + v_max = boundary + particles = [particle(dimension, boundary, v_max, function_d, pos) + for pos in lhs.latin_hypercube(dimension, bound, n_parts)] gl_best = max(particles) for _ in xrange(n_turns): - move_p = partial(move, omega=0.9, phi_p=0.9, phi_g=0.2, v_max=20., + move_p = partial(move, + omega=0.98, phi_p=2.75, phi_g=3., v_max=v_max, global_best=gl_best[1], func_d=function_d) particles = pool.map(move_p, particles) gl_best = max(max(particles), gl_best)