Skip to content

Commit

Permalink
Merge pull request DEAP#713 from bje-/flake8-fixes
Browse files Browse the repository at this point in the history
flake8 fixes
  • Loading branch information
fmder authored Jul 23, 2023
2 parents e4f816a + ef05d4b commit 2fbef3f
Show file tree
Hide file tree
Showing 21 changed files with 153 additions and 144 deletions.
2 changes: 1 addition & 1 deletion deap/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,4 +355,4 @@ def __repr__(self):
"""Return the Python code to build a copy of the object."""
return "%s.%s(%r, %r)" % (self.__module__, self.__class__.__name__,
self.values if self.valid else tuple(),
self.constraint_violation)
self.constraint_violation)
22 changes: 12 additions & 10 deletions deap/benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def rosenbrock(individual):
.. plot:: code/benchmarks/rosenbrock.py
:width: 67 %
"""
return sum(100 * (x * x - y)**2 + (1. - x)**2 \
return sum(100 * (x * x - y)**2 + (1. - x)**2
for x, y in zip(individual[:-1], individual[1:])),


Expand Down Expand Up @@ -245,7 +245,7 @@ def rastrigin(individual):
.. plot:: code/benchmarks/rastrigin.py
:width: 67 %
"""
return 10 * len(individual) + sum(gene * gene - 10 * \
return 10 * len(individual) + sum(gene * gene - 10 *
cos(2 * pi * gene) for gene in individual),


Expand Down Expand Up @@ -273,8 +273,10 @@ def rastrigin_skew(individual):
\end{cases}`
"""
N = len(individual)
return 10*N + sum((10*x if x > 0 else x)**2
- 10*cos(2*pi*(10*x if x > 0 else x)) for x in individual),
return 10 * N + sum((10 * x if x > 0 else x) ** 2
- 10 * cos(2 * pi * (10 * x if x > 0 else x)) for x in individual),


def schaffer(individual):
r"""Schaffer test objective function.
Expand Down Expand Up @@ -539,7 +541,7 @@ def dtlz2(individual, obj):
xm = individual[obj - 1:]
g = sum((xi - 0.5)**2 for xi in xm)
f = [(1.0 + g) * reduce(mul, (cos(0.5 * xi * pi) for xi in xc), 1.0)]
f.extend((1.0 + g) * reduce(mul, (cos(0.5 * xi * pi) for xi in xc[:m]), 1) * sin(0.5 * xc[m]*pi) for m in range(obj-2, -1, -1))
f.extend((1.0 + g) * reduce(mul, (cos(0.5 * xi * pi) for xi in xc[:m]), 1) * sin(0.5 * xc[m] * pi) for m in range(obj - 2, -1, -1))

return f

Expand Down Expand Up @@ -650,9 +652,9 @@ def dtlz7(ind, n_objs):
From: K. Deb, L. Thiele, M. Laumanns and E. Zitzler. Scalable Multi-Objective
Optimization Test Problems. CEC 2002, p. 825-830, IEEE Press, 2002.
"""
gval = 1 + 9.0 / len(ind[n_objs-1:]) * sum([a for a in ind[n_objs-1:]])
fit = [x for x in ind[:n_objs-1]]
fit.append((1 + gval) * (n_objs - sum([a / (1.0 + gval) * (1 + sin(3 * pi * a)) for a in ind[:n_objs-1]])))
gval = 1 + 9.0 / len(ind[n_objs - 1:]) * sum([a for a in ind[n_objs - 1:]])
fit = [x for x in ind[:n_objs - 1]]
fit.append((1 + gval) * (n_objs - sum([a / (1.0 + gval) * (1 + sin(3 * pi * a)) for a in ind[:n_objs - 1]])))
return fit


Expand All @@ -667,8 +669,8 @@ def fonseca(individual):
:math:`f_{\text{Fonseca}2}(\mathbf{x}) = 1 - e^{-\sum_{i=1}^{3}(x_i + \frac{1}{\sqrt{3}})^2}`
"""
f_1 = 1 - exp(-sum((xi - 1/sqrt(3))**2 for xi in individual[:3]))
f_2 = 1 - exp(-sum((xi + 1/sqrt(3))**2 for xi in individual[:3]))
f_1 = 1 - exp(-sum((xi - 1 / sqrt(3)) ** 2 for xi in individual[:3]))
f_2 = 1 - exp(-sum((xi + 1 / sqrt(3)) ** 2 for xi in individual[:3]))
return f_1, f_2


Expand Down
42 changes: 21 additions & 21 deletions deap/benchmarks/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ def wrapped_function(individual, *args, **kargs):
decoded = [0] * nelem
for i in range(nelem):
gene = int("".join(map(str,
individual[i*nbits:i*nbits+nbits])),
individual[i * nbits:i * nbits + nbits])),
2)
div = 2**nbits - 1
temp = gene/div
temp = gene / div
decoded[i] = min_ + (temp * (max_ - min_))
return function(decoded, *args, **kargs)
return wrapped_function
Expand Down Expand Up @@ -67,11 +67,11 @@ def chuang_f1(individual):
"""
total = 0
if individual[-1] == 0:
for i in range(0, len(individual)-1, 4):
total += inv_trap(individual[i:i+4])
for i in range(0, len(individual) - 1, 4):
total += inv_trap(individual[i:i + 4])
else:
for i in range(0, len(individual)-1, 4):
total += trap(individual[i:i+4])
for i in range(0, len(individual) - 1, 4):
total += trap(individual[i:i + 4])
return total,


Expand All @@ -84,17 +84,17 @@ def chuang_f2(individual):
"""
total = 0
if individual[-2] == 0 and individual[-1] == 0:
for i in range(0, len(individual)-2, 8):
total += inv_trap(individual[i:i+4]) + inv_trap(individual[i+4:i+8])
for i in range(0, len(individual) - 2, 8):
total += inv_trap(individual[i:i + 4]) + inv_trap(individual[i + 4:i + 8])
elif individual[-2] == 0 and individual[-1] == 1:
for i in range(0, len(individual)-2, 8):
total += inv_trap(individual[i:i+4]) + trap(individual[i+4:i+8])
for i in range(0, len(individual) - 2, 8):
total += inv_trap(individual[i:i + 4]) + trap(individual[i + 4:i + 8])
elif individual[-2] == 1 and individual[-1] == 0:
for i in range(0, len(individual)-2, 8):
total += trap(individual[i:i+4]) + inv_trap(individual[i+4:i+8])
for i in range(0, len(individual) - 2, 8):
total += trap(individual[i:i + 4]) + inv_trap(individual[i + 4:i + 8])
else:
for i in range(0, len(individual)-2, 8):
total += trap(individual[i:i+4]) + trap(individual[i+4:i+8])
for i in range(0, len(individual) - 2, 8):
total += trap(individual[i:i + 4]) + trap(individual[i + 4:i + 8])
return total,


Expand All @@ -107,12 +107,12 @@ def chuang_f3(individual):
"""
total = 0
if individual[-1] == 0:
for i in range(0, len(individual)-1, 4):
total += inv_trap(individual[i:i+4])
for i in range(0, len(individual) - 1, 4):
total += inv_trap(individual[i:i + 4])
else:
for i in range(2, len(individual)-3, 4):
total += inv_trap(individual[i:i+4])
total += trap(individual[-2:]+individual[:2])
for i in range(2, len(individual) - 3, 4):
total += inv_trap(individual[i:i + 4])
total += trap(individual[-2:] + individual[:2])
return total,


Expand All @@ -125,8 +125,8 @@ def royal_road1(individual, order):
max_value = int(2**order - 1)
total = 0
for i in range(nelem):
value = int("".join(map(str, individual[i*order:i*order+order])), 2)
total += int(order) * int(value/max_value)
value = int("".join(map(str, individual[i * order:i * order + order])), 2)
total += int(order) * int(value / max_value)
return total,


Expand Down
5 changes: 1 addition & 4 deletions deap/benchmarks/movingpeaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@
import itertools
import random

try:
from collections.abc import Sequence
except:
from collections import Sequence
from collections.abc import Sequence


def cone(individual, position, height, width):
Expand Down
8 changes: 4 additions & 4 deletions deap/benchmarks/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class scale(object):
def __init__(self, factor):
# Factor is inverted since it is applied to the individual and not the
# objective function
self.factor = tuple(1.0/f for f in factor)
self.factor = tuple(1.0 / f for f in factor)

def __call__(self, func):
# wraps is used to combine stacked decorators that would add functions
Expand All @@ -211,7 +211,7 @@ def evaluate(individual):
"""
# Factor is inverted since it is applied to the individual and not the
# objective function
self.factor = tuple(1.0/f for f in factor)
self.factor = tuple(1.0 / f for f in factor)


class bound(object):
Expand Down Expand Up @@ -276,9 +276,9 @@ def diversity(first_front, first, last):
if len(first_front) == 1:
return df + dl

dm = sum(dt)/len(dt)
dm = sum(dt) / len(dt)
di = sum(abs(d_i - dm) for d_i in dt)
delta = (df + dl + di)/(df + dl + len(dt) * dm)
delta = (df + dl + di) / (df + dl + len(dt) * dm)
return delta


Expand Down
10 changes: 5 additions & 5 deletions deap/cma.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ def generate(self, ind_init):
round_values = numpy.tile(self.S_int > 0, (self.lambda_, 1))
steps = numpy.tile(self.S_int, (self.lambda_, 1))
x[round_values] = steps[round_values] * numpy.around(x[round_values]
/ steps[round_values])
/ steps[round_values])

# The update method requires to remember the y of each individual
population = list(map(ind_init, x))
Expand Down Expand Up @@ -722,7 +722,7 @@ def _integer_mutation(self):
# Probabilistically choose lambda_int individuals
if numpy.random.rand() < p:
Rp[i, j] = 1
Rpp[i, j] = numpy.random.geometric(p=0.7**(1.0/n_I_R)) - 1
Rpp[i, j] = numpy.random.geometric(p=0.7**(1.0 / n_I_R)) - 1

I_pm1 = (-1)**numpy.random.randint(0, 2, (self.lambda_, self.dim))
R_int = I_pm1 * (Rp + Rpp)
Expand Down Expand Up @@ -809,7 +809,7 @@ def _infeasible_update(self, individual):
for i in range(self.constraint_vecs.shape[0]):
if individual.fitness.constraint_violation[i]:
self.constraint_vecs[i] = (1 - self.cconst) * self.constraint_vecs[i] \
+ self.cconst * individual._y
+ self.cconst * individual._y

W = numpy.dot(self.invA, self.constraint_vecs.T).T # M x N
constraint_violation = numpy.sum(individual.fitness.constraint_violation)
Expand Down Expand Up @@ -855,7 +855,7 @@ def update(self, population):
self._rank1update(valid_population[0],
float(lambda_succ) / len(valid_population))

if len(invalid_population) > 0 :
if len(invalid_population) > 0:
# Learn constraint from all invalid individuals
for ind in invalid_population:
self._infeasible_update(ind)
Expand All @@ -865,4 +865,4 @@ def update(self, population):

C = numpy.dot(self.A, self.A.T)
self.i_I_R = numpy.flatnonzero(2 * self.sigma * numpy.diag(C)**0.5
< self.S_int)
< self.S_int)
16 changes: 10 additions & 6 deletions deap/gp.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import sys
import types
import warnings
from inspect import isclass

from collections import defaultdict, deque
from functools import partial, wraps
Expand Down Expand Up @@ -240,12 +241,14 @@ def __eq__(self, other):
else:
return NotImplemented


class MetaEphemeral(type):
"""Meta-Class that creates a terminal which value is set when the
object is created. To mutate the value, a new object has to be
generated.
"""
cache = {}

def __new__(meta, name, func, ret=__type__, id_=None):
if id_ in MetaEphemeral.cache:
return MetaEphemeral.cache[id_]
Expand All @@ -259,11 +262,11 @@ def __new__(meta, name, func, ret=__type__, id_=None):
def __init__(self):
self.value = func()

attr = {'__init__' : __init__,
'name' : name,
'func' : func,
'ret' : ret,
'conv_fct' : repr}
attr = {'__init__': __init__,
'name': name,
'func': func,
'ret': ret,
'conv_fct': repr}

cls = super(MetaEphemeral, meta).__new__(meta, name, (Terminal,), attr)
MetaEphemeral.cache[id(cls)] = cls
Expand All @@ -275,6 +278,7 @@ def __init__(cls, name, func, ret=__type__, id_=None):
def __reduce__(cls):
return (MetaEphemeral, (cls.name, cls.func, cls.ret, id(cls)))


copyreg.pickle(MetaEphemeral, MetaEphemeral.__reduce__)


Expand Down Expand Up @@ -411,7 +415,7 @@ def addEphemeralConstant(self, name, ephemeral, ret_type):
:param ephemeral: function with no arguments returning a random value.
:param ret_type: type of the object returned by *ephemeral*.
"""
if not name in self.mapping:
if name not in self.mapping:
class_ = MetaEphemeral(name, ephemeral, ret_type)
else:
class_ = self.mapping[name]
Expand Down
2 changes: 1 addition & 1 deletion deap/tools/_hypervolume/pyhv.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def hvRecursive(self, dimIndex, length, bounds):
hvRecursive = self.hvRecursive
p = sentinel
q = p.prev[dimIndex]
while q.cargo != None:
while q.cargo is not None:
if q.ignore < dimIndex:
q.ignore = 0
q = q.prev[dimIndex]
Expand Down
Loading

0 comments on commit 2fbef3f

Please sign in to comment.