Friday, June 24, 2011

Optimize any Python Function using Particle Swarm


The code given below was used to generate parameter set for making a non-monotonic input-output steady state plot. The code uses Particle Swarm optimization algorithm. It allows multiple runs of the algorithm for finding multiple minima.



from tinkercell import *
from tc2py import *
from numpy import *
from PSO import *  #particle swarm optimization (included with TinkerCell)
nameOfInput ="INPUT" #name of input variable in the model
nameOfOutput ="OUTPUT" #name of output variable in the model
params = tc_createMatrix(1,1)
tc_setRowName(params,0,nameOfInput)
def Objective():
    tc_setMatrixValue(params, 0, 0, 0.1)
    tc_updateParameters(params)
    ss = tc_getSteadyState()
    i = tc_getRowIndex(ss, nameOfOutput)
    x1 = tc_getMatrixValue(ss, i, 0)
    tc_setMatrixValue(params, 0, 0, 2)
    tc_updateParameters(params)
    ss = tc_getSteadyState()
    x2 = tc_getMatrixValue(ss, i, 0)
    tc_setMatrixValue(params, 0, 0, 5)
    tc_updateParameters(params)
    ss = tc_getSteadyState()
    x3 = tc_getMatrixValue(ss, i, 0)
    if x3 > x1: x1 = x3
    return (x2 - x1)
optimizer = ParticleSwarm()
#minimize or maximize?
optimizer.numpoints = 50
optimizer.maxiter = 10
optimizer.minimize = False
optimizer.title = "Nonmonotic test"
g = optimizer.run(Objective,10) #multiple runs

No comments: