Skip to content

Base

deap_er.Toolbox()

A container for evolutionary operators.

Registers callables under aliases so algorithms can request mate, mutate, select, evaluate, and similar tools without hard-coding implementations.

Register the default clone and map operators.

Source code in deap_er/private/toolbox.py
def __init__(self) -> None:
    """Register the default ``clone`` and ``map`` operators."""
    self.register("clone", deepcopy)
    self.register("map", map)

__getattr__(name)

Resolve aliases bound by register.

register attaches names with setattr. This hook is for the type checker and for missing aliases at runtime.

Parameters:

Name Type Description Default
name str

Operator alias.

required

Raises:

Type Description
AttributeError

If name is not registered.

Source code in deap_er/private/toolbox.py
def __getattr__(self, name: str) -> Any:
    """Resolve aliases bound by ``register``.

    ``register`` attaches names with ``setattr``. This hook is
    for the type checker and for missing aliases at runtime.

    Args:
        name: Operator alias.

    Raises:
        AttributeError: If ``name`` is not registered.
    """
    raise AttributeError(name)

register(alias, func, *args, **kwargs)

Bind func to alias on this toolbox.

Extra positional and keyword arguments are bound into the registered callable. Callers may still override those bound values when they invoke the alias.

Parameters:

Name Type Description Default
alias str

Name to register. Overwrites an existing alias of the same name.

required
func Callable[..., Any]

Callable the alias will refer to.

required
*args Any

Positional arguments bound into func.

()
**kwargs Any

Keyword arguments bound into func.

{}
Source code in deap_er/private/toolbox.py
def register(self, alias: str, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
    """Bind ``func`` to ``alias`` on this toolbox.

    Extra positional and keyword arguments are bound into the
    registered callable. Callers may still override those bound
    values when they invoke the alias.

    Args:
        alias: Name to register. Overwrites an existing alias of the same name.
        func: Callable the alias will refer to.
        *args: Positional arguments bound into ``func``.
        **kwargs: Keyword arguments bound into ``func``.
    """
    p_func: Any = partial(func, *args, **kwargs)
    p_func.__name__ = alias
    p_func.__doc__ = func.__doc__

    if hasattr(func, "__dict__") and not isinstance(func, type):
        p_func.__dict__.update(func.__dict__.copy())
    setattr(self, alias, p_func)

unregister(alias)

Remove the operator registered as alias.

Parameters:

Name Type Description Default
alias str

Name of the operator to remove.

required
Source code in deap_er/private/toolbox.py
def unregister(self, alias: str) -> None:
    """Remove the operator registered as ``alias``.

    Args:
        alias: Name of the operator to remove.
    """
    delattr(self, alias)

decorate(alias, *decorators)

Wrap the operator alias with one or more decorators.

Parameters:

Name Type Description Default
alias str

Name of a registered operator.

required
*decorators Callable[..., Any]

Decorators applied left to right. If omitted, the operator is left unchanged.

()
Source code in deap_er/private/toolbox.py
def decorate(self, alias: str, *decorators: Callable[..., Any]) -> None:
    """Wrap the operator ``alias`` with one or more decorators.

    Args:
        alias: Name of a registered operator.
        *decorators: Decorators applied left to right. If omitted, the
            operator is left unchanged.
    """
    if not decorators:
        return
    p_func = getattr(self, alias)
    func = p_func.func
    args = p_func.args
    kwargs = p_func.keywords
    for decorator in decorators:
        func = decorator(func)
    self.register(alias, func, *args, **kwargs)

deap_er.Fitness(values=None)

Quality of a solution, compared through weighted objectives.

The class attribute weights must be set before a Fitness object can be instantiated. A fitness may be created without values, but it stays invalid until values is assigned a sequence of the same length as weights.

Parameters:

Name Type Description Default
values FitnessValues | None

Initial objective values. Optional.

None

Attributes:

Name Type Description
weights Sequence[int | float]

Shared per fitness type. Each element is a real number for one objective: negative means minimize, positive means maximize.

See the class docstring.

Source code in deap_er/private/fitness.py
def __init__(self, values: FitnessValues | None = None) -> None:
    """See the class docstring."""
    if not self.weights:
        raise TypeError(
            "Can't instantiate 'Fitness', when class attribute 'weights' tuple is not set."
        )
    if values is not None:
        self.values = values

values deletable property writable

Objective values of the individual.

The setter accepts a number, a 0-d NumPy array, or a sequence of numbers. A single number is stored as a one-element sequence. The getter returns a tuple of floats, or an empty tuple when the fitness is invalid. Deleting the property clears the stored values.

Raises:

Type Description
TypeError

If the assigned sequence length does not match weights.

dominates(other, slc=None)

Return whether this fitness Pareto-dominates other.

Each compared objective of self must be at least as good as the corresponding objective of other, and at least one must be strictly better.

Parameters:

Name Type Description Default
other Fitness

Fitness to test against.

required
slc slice | None

Slice of objectives to compare. Optional; all objectives are used when omitted.

None

Returns:

Type Description
bool

True if self dominates other. False if either

bool

fitness is invalid or the compared lengths differ.

Source code in deap_er/private/fitness.py
def dominates(self, other: Fitness, slc: slice | None = None) -> bool:
    """Return whether this fitness Pareto-dominates ``other``.

    Each compared objective of ``self`` must be at least as good as
    the corresponding objective of ``other``, and at least one must
    be strictly better.

    Args:
        other: Fitness to test against.
        slc: Slice of objectives to compare. Optional; all
            objectives are used when omitted.

    Returns:
        True if ``self`` dominates ``other``. False if either
        fitness is invalid or the compared lengths differ.
    """
    own = self.wvalues if slc is None else self.wvalues[slc]
    theirs = other.wvalues if slc is None else other.wvalues[slc]
    n = len(own)
    if n == 0 or n != len(theirs):
        return False
    if n == 3:
        return _dominates_triple(own, theirs)
    if n == 2:
        return _dominates_pair(own, theirs)
    if n == 1:
        return own[0] > theirs[0]
    better = False
    for i in range(n):
        a = own[i]
        b = theirs[i]
        if a < b:
            return False
        if a > b:
            better = True
    return better

is_valid()

Return whether this fitness has a complete set of values.

Returns:

Type Description
bool

True if weights is non-empty and values has the

bool

same length.

Source code in deap_er/private/fitness.py
def is_valid(self) -> bool:
    """Return whether this fitness has a complete set of values.

    Returns:
        True if ``weights`` is non-empty and ``values`` has the
        same length.
    """
    return len(self.wvalues) == len(self.weights) > 0

__gt__(other)

Return whether this fitness is strictly better than other.

Source code in deap_er/private/fitness.py
def __gt__(self, other: Fitness) -> bool:
    """Return whether this fitness is strictly better than ``other``."""
    return self.wvalues > other.wvalues

__ge__(other)

Return whether this fitness is at least as good as other.

Source code in deap_er/private/fitness.py
def __ge__(self, other: Fitness) -> bool:
    """Return whether this fitness is at least as good as ``other``."""
    return self.wvalues >= other.wvalues

__le__(other)

Return whether this fitness is at most as good as other.

Source code in deap_er/private/fitness.py
def __le__(self, other: Fitness) -> bool:
    """Return whether this fitness is at most as good as ``other``."""
    return self.wvalues <= other.wvalues

__lt__(other)

Return whether this fitness is strictly worse than other.

Source code in deap_er/private/fitness.py
def __lt__(self, other: Fitness) -> bool:
    """Return whether this fitness is strictly worse than ``other``."""
    return self.wvalues < other.wvalues

__eq__(other)

Return whether the two fitnesses compare equal.

Source code in deap_er/private/fitness.py
@override
def __eq__(self, other: object) -> bool:
    """Return whether the two fitnesses compare equal."""
    if not isinstance(other, Fitness):
        return NotImplemented
    return self.wvalues == other.wvalues

__ne__(other)

Return whether the two fitnesses compare unequal.

Source code in deap_er/private/fitness.py
@override
def __ne__(self, other: object) -> bool:
    """Return whether the two fitnesses compare unequal."""
    if not isinstance(other, Fitness):
        return NotImplemented
    return self.wvalues != other.wvalues

__len__()

Return the number of stored weighted values.

Source code in deap_er/private/fitness.py
def __len__(self) -> int:
    """Return the number of stored weighted values."""
    return len(self.wvalues)

__hash__()

Hash the weighted values.

Source code in deap_er/private/fitness.py
@override
def __hash__(self) -> int:
    """Hash the weighted values."""
    return hash(self.wvalues)

__str__()

Return the unweighted values as a string.

Source code in deap_er/private/fitness.py
@override
def __str__(self) -> str:
    """Return the unweighted values as a string."""
    return str(self.values)

__repr__()

Return a reconstructable representation.

Source code in deap_er/private/fitness.py
@override
def __repr__(self) -> str:
    """Return a reconstructable representation."""
    return f"{self.__module__}.{self.__class__.__name__}({str(self.values)})"

__deepcopy__(memo)

Return a new Fitness with the same weighted values.

Source code in deap_er/private/fitness.py
def __deepcopy__(self, memo: dict[int, Any]) -> Fitness:
    """Return a new Fitness with the same weighted values."""
    copy = self.__class__()
    copy.wvalues = self.wvalues
    copy._values = self._values
    return copy