pythondeap

register multiple parameters to an individual using DEAP


I have to integrate DEAP into a bigger frame work.

For testing I defined:

from deap import base
from deap import creator
from deap import tools
from collections import *
import random

NAME = 0
TYPE = 1
INITIAL = 2
MIN = 3
MAX = 4
CATEGORY = 5

IND_SIZE = 1

Data = OrderedDict()
Data['P1'] = ['distance' , float, 8.     ,7.9    ,8.1  , [] ]
Data['P2'] = ['velocity' , float, 80.    ,79.7   ,83.3 , [] ]
Data['P3'] = ['rigid'    , int  , 0      ,0      ,1    , ['false','true'] ]

toolbox = base.Toolbox()

for Key in Data:
    if Data[Key][TYPE] is float:
        toolbox.register(Data[Key][NAME], random.uniform, Data[Key][MIN], Data[Key][MAX])
    if Data[Key][TYPE] is int:
        toolbox.register(Data[Key][NAME], random.randint, Data[Key][MIN], Data[Key][MAX])

AttrSet = (toolbox.distance, toolbox.velocity,  toolbox.rigid)
toolbox.register("individual", tools.initCycle, creator.individual, AttrSet, IND_SIZE)

This runs as expected, but if the framework delivers Data with different len() AttrSet has to be changed, too

Is there a way to create AttrSet from Data, e.g. in the loop where the parameters are registered?

toolbox.register() always returns None, so this is not working.


Solution

  • You could use the Python built-in function getattr, which lets you get attributes of an object by name.

    As explained in the docs: getattr(x, 'foobar') is equivalent to x.foobar.

    So you could do something like:

    toolbox = base.Toolbox()
    
    AttrSet = []
    
    for Key in Data:
        if Data[Key][TYPE] is float:
            toolbox.register(Data[Key][NAME], random.uniform, Data[Key][MIN], Data[Key][MAX])
        elif Data[Key][TYPE] is int:
            toolbox.register(Data[Key][NAME], random.randint, Data[Key][MIN], Data[Key][MAX])
    
        AttrSet.append(getattr(toolbox, Data[Key][NAME]))
    
    toolbox.register("individual", tools.initCycle, creator.individual, AttrSet, IND_SIZE)