Skip to content

DEAP Creator Utilities

The :mod:~deap.creator is a meta-factory allowing to create classes that will fulfill the needs of your evolutionary algorithms. In effect, new classes can be built from any imaginable type, from :class:list to :class:set, :class:dict, :class:~deap.gp.PrimitiveTree and more, providing the possibility to implement genetic algorithms, genetic programming, evolution strategies, particle swarm optimizers, and many more.

class_replacers = {} module-attribute

Some classes in Python's standard library as well as third party library may be in part incompatible with the logic used in DEAP. To palliate this problem, the method :func:create uses the dictionary class_replacers to identify if the base type provided is problematic, and if so the new class inherits from the replacement class instead of the original base class. class_replacers keys are classes to be replaced and the values are the replacing classes.

MetaCreator

Bases: type

Source code in xopt/generators/ga/deap_creator.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
class MetaCreator(type):
    def __new__(meta, name, base, dct):
        return super(MetaCreator, meta).__new__(meta, name, (base,), dct)

    def __init__(cls, name, base, dct):
        # A DeprecationWarning is raised when the object inherits from the
        # class "object" which leave the option of passing arguments, but
        # raise a warning stating that it will eventually stop permitting
        # this option. Usually this happens when the base class does not
        # override the __init__ method from object.
        dict_inst = {}
        dict_cls = {}
        for obj_name, obj in dct.items():
            if isinstance(obj, type):
                dict_inst[obj_name] = obj
            else:
                dict_cls[obj_name] = obj

        def initType(self, *args, **kargs):
            """Replace the __init__ function of the new type, in order to
            add attributes that were defined with **kargs to the instance.
            """
            for obj_name, obj in dict_inst.items():
                setattr(self, obj_name, obj())
            if base.__init__ is not object.__init__:
                base.__init__(self, *args, **kargs)

        cls.__init__ = initType
        cls.reduce_args = (name, base, dct)
        super(MetaCreator, cls).__init__(name, (base,), dict_cls)

    def __reduce__(cls):
        return (meta_create, cls.reduce_args)

__init__(name, base, dct)

Source code in xopt/generators/ga/deap_creator.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def __init__(cls, name, base, dct):
    # A DeprecationWarning is raised when the object inherits from the
    # class "object" which leave the option of passing arguments, but
    # raise a warning stating that it will eventually stop permitting
    # this option. Usually this happens when the base class does not
    # override the __init__ method from object.
    dict_inst = {}
    dict_cls = {}
    for obj_name, obj in dct.items():
        if isinstance(obj, type):
            dict_inst[obj_name] = obj
        else:
            dict_cls[obj_name] = obj

    def initType(self, *args, **kargs):
        """Replace the __init__ function of the new type, in order to
        add attributes that were defined with **kargs to the instance.
        """
        for obj_name, obj in dict_inst.items():
            setattr(self, obj_name, obj())
        if base.__init__ is not object.__init__:
            base.__init__(self, *args, **kargs)

    cls.__init__ = initType
    cls.reduce_args = (name, base, dct)
    super(MetaCreator, cls).__init__(name, (base,), dict_cls)

create(name, base, **kargs)

Creates a new class named name inheriting from base in the :mod:~deap.creator module. The new class can have attributes defined by the subsequent keyword arguments passed to the function create. If the argument is a class (without the parenthesis), the init function is called in the initialization of an instance of the new object and the returned instance is added as an attribute of the class' instance. Otherwise, if the argument is not a class, (for example an :class:int), it is added as a "static" attribute of the class.

:param name: The name of the class to create. :param base: A base class from which to inherit. :param attribute: One or more attributes to add on instanciation of this class, optional.

The following is used to create a class :class:Foo inheriting from the standard :class:list and having an attribute :attr:bar being an empty dictionary and a static attribute :attr:spam initialized to 1. ::

create("Foo", list, bar=dict, spam=1)

This above line is exactly the same as defining in the :mod:creator module something like the following. ::

class Foo(list):
    spam = 1

    def __init__(self):
        self.bar = dict()

The :ref:creating-types tutorial gives more examples of the creator usage.

.. warning::

If your are inheriting from :class:numpy.ndarray see the :doc:tutorials/advanced/numpy tutorial and the :doc:/examples/ga_onemax_numpy example.

Source code in xopt/generators/ga/deap_creator.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def create(name, base, **kargs):
    """Creates a new class named *name* inheriting from *base* in the
    :mod:`~deap.creator` module. The new class can have attributes defined by
    the subsequent keyword arguments passed to the function create. If the
    argument is a class (without the parenthesis), the __init__ function is
    called in the initialization of an instance of the new object and the
    returned instance is added as an attribute of the class' instance.
    Otherwise, if the argument is not a class, (for example an :class:`int`),
    it is added as a "static" attribute of the class.

    :param name: The name of the class to create.
    :param base: A base class from which to inherit.
    :param attribute: One or more attributes to add on instanciation of this
                      class, optional.

    The following is used to create a class :class:`Foo` inheriting from the
    standard :class:`list` and having an attribute :attr:`bar` being an empty
    dictionary and a static attribute :attr:`spam` initialized to 1. ::

        create("Foo", list, bar=dict, spam=1)

    This above line is exactly the same as defining in the :mod:`creator`
    module something like the following. ::

        class Foo(list):
            spam = 1

            def __init__(self):
                self.bar = dict()
    The :ref:`creating-types` tutorial gives more examples of the creator
    usage.

    .. warning::

       If your are inheriting from :class:`numpy.ndarray` see the
       :doc:`tutorials/advanced/numpy` tutorial and the
       :doc:`/examples/ga_onemax_numpy` example.
    """

    if name in globals():
        warnings.warn(
            "A class named '{0}' has already been created and it "
            "will be overwritten. Consider deleting previous "
            "creation of that class or rename it.".format(name),
            RuntimeWarning,
        )

    # Check if the base class has to be replaced
    if base in class_replacers:
        base = class_replacers[base]
    meta_create(name, base, kargs)