File: pso.py

package info (click to toggle)
python-scipy 0.6.0-12
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 32,016 kB
  • ctags: 46,675
  • sloc: cpp: 124,854; ansic: 110,614; python: 108,664; fortran: 76,260; objc: 424; makefile: 384; sh: 10
file content (60 lines) | stat: -rw-r--r-- 1,671 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Particle Swarm Optimization

:Author: Robert Kern

Copyright 2005 by Robert Kern.
"""

import scipy as sp

def pso(func, nswarm, lbound, ubound, vmax, args=(), maxiter=1000, cp=2.0, cg=2.0):
    ndim = len(lbound)
    lbound = sp.asarray(lbound)
    ubound = sp.asarray(ubound)
    vmax = sp.asarray(vmax)

    # initialize the swarm
    swarm = lbound + sp.rand(nswarm, ndim)*(ubound-lbound)

    # initialize the "personal best" values
    pbestv = sp.zeros(nswarm, sp.Float)
    for i in sp.arange(nswarm):
        pbestv[i] = func(swarm[i])
    pbest = sp.array(swarm)

    # initialize the "global best" values
    gbesti = sp.argmin(pbestv)
    gbestv = pbestv[gbesti]
    gbest = pbest[gbesti]

    # initialize velocities
    velocities = 2*vmax*sp.randn(nswarm, ndim) - vmax

    for i in sp.arange(maxiter):

        values = sp.zeros(nswarm, sp.Float)
        for j in sp.arange(nswarm):
            values[j] = func(swarm[j])

        mask = values < pbestv
        mask2d = sp.repeat(mask, ndim)
        mask2d.shape = (nswarm, ndim)
        pbestv = sp.where(mask, values, pbestv)
        pbest = sp.where(mask2d, swarm, pbest)

        if sp.minimum.reduce(pbestv) < gbestv:
            gbesti = sp.argmin(pbestv)
            gbestv = pbestv[gbesti]
            gbest = pbest[gbesti]

        velocities += (cp*sp.rand()*(pbest - swarm) +
                       cg*sp.rand()*(gbest - swarm))
        velocities = sp.clip(velocities, -vmax, vmax)
        swarm += velocities
        swarm = sp.clip(swarm, lbound, ubound)
        yield gbest

##    return gbest

def _testfunc(x):
    return -sp.multiply.reduce(sp.cos(x/2.0/sp.pi))*sp.exp(-sp.sum(x*x))