Project-Platypus / Platypus

A Free and Open Source Python Library for Multiobjective Optimization
GNU General Public License v3.0
569 stars 153 forks source link

Example with passing parameters to function #52

Closed vzografos closed 2 years ago

vzografos commented 6 years ago

Hi, can you provide a simple example how to pass non-decision variable parameters to the objective function?

Thank you

dhadka commented 6 years ago

Sure. Platypus assumes that the function it's given takes a single argument, the list of decision variable values. To support non-decision variable parameters, you just need to create a version of the function that satisfies this condition. For example:


import functools
from platypus import NSGAII, Problem, Real

def myproblem(x, arg1, arg2=5):
    print("x:", x)
    print("arg1:", arg1)
    print("arg2:", arg2)

    return [x[0]**2, (x[0]-2)**2]

problem = Problem(1, 2)
problem.types[:] = Real(-10, 10)
problem.function = functools.partial(myproblem, arg1=2)

algorithm = NSGAII(problem)
algorithm.run(100)

In the above example, we have two non-decision variable arguments: arg1 and arg2. For arg1, we must assign a value using:

functools.partial(myproblem, arg1=2)

arg2 already has a default value so we do not need to specify a value. If you wanted to change the value of arg2, you would use:

functools.partial(myproblem, arg1=2, arg2=10)