Skip to content

Commit

Permalink
Round one of flake8 warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
bje- committed Apr 24, 2023
1 parent 69da33c commit 8aa17a0
Show file tree
Hide file tree
Showing 18 changed files with 86 additions and 24 deletions.
12 changes: 11 additions & 1 deletion deap/benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from operator import mul
from functools import reduce


# Unimodal
def rand(individual):
r"""Random test objective function.
Expand All @@ -41,6 +42,7 @@ def rand(individual):
"""
return random.random(),


def plane(individual):
r"""Plane test objective function.
Expand All @@ -59,6 +61,7 @@ def plane(individual):
"""
return individual[0],


def sphere(individual):
r"""Sphere test objective function.
Expand All @@ -77,6 +80,7 @@ def sphere(individual):
"""
return sum(gene * gene for gene in individual),


def cigar(individual):
r"""Cigar test objective function.
Expand All @@ -95,6 +99,7 @@ def cigar(individual):
"""
return individual[0]**2 + 1e6 * sum(gene * gene for gene in individual[1:]),


def rosenbrock(individual):
r"""Rosenbrock test objective function.
Expand All @@ -117,6 +122,7 @@ def rosenbrock(individual):
return sum(100 * (x * x - y)**2 + (1. - x)**2 \
for x, y in zip(individual[:-1], individual[1:])),


def h1(individual):
r""" Simple two-dimensional function containing several local maxima.
From: The Merits of a Parallel Genetic Algorithm in Solving Hard
Expand Down Expand Up @@ -145,7 +151,7 @@ def h1(individual):
denum = ((individual[0] - 8.6998)**2 + (individual[1] - 6.7665)**2)**0.5 + 1
return num / denum,

#

# Multimodal
def ackley(individual):
r"""Ackley test objective function.
Expand Down Expand Up @@ -596,6 +602,7 @@ def dtlz5(ind, n_objs):
reduce(lambda x,y: x*y, [cos(theta(a)) for a in ind[1:m-1]], 1) * sin(theta(ind[m-1])))
return fit


def dtlz6(ind, n_objs):
r"""DTLZ6 multiobjective function. It returns a tuple of *obj* values. The
individual must have at least *obj* elements.
Expand All @@ -616,6 +623,7 @@ def dtlz6(ind, n_objs):
reduce(lambda x,y: x*y, [cos(theta(a)) for a in ind[1:m-1]], 1) * sin(theta(ind[m-1])))
return fit


def dtlz7(ind, n_objs):
r"""DTLZ7 multiobjective function. It returns a tuple of *obj* values. The
individual must have at least *obj* elements.
Expand All @@ -627,6 +635,7 @@ def dtlz7(ind, n_objs):
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


def fonseca(individual):
r"""Fonseca and Fleming's multiobjective function.
From: C. M. Fonseca and P. J. Fleming, "Multiobjective optimization and
Expand All @@ -642,6 +651,7 @@ def fonseca(individual):
f_2 = 1 - exp(-sum((xi + 1/sqrt(3))**2 for xi in individual[:3]))
return f_1, f_2


def poloni(individual):
r"""Poloni's multiobjective function on a two attribute *individual*. From:
C. Poloni, "Hybrid GA for multi objective aerodynamic shape optimization",
Expand Down
10 changes: 9 additions & 1 deletion deap/benchmarks/gp.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from math import exp, sin, cos


def kotanchek(data):
"""Kotanchek benchmark function.
Expand All @@ -29,6 +30,7 @@ def kotanchek(data):
"""
return exp(-(data[0] - 1)**2) / (3.2 + (data[1] - 2.5)**2)


def salustowicz_1d(data):
"""Salustowicz benchmark function.
Expand All @@ -43,8 +45,9 @@ def salustowicz_1d(data):
"""
return exp(-data[0]) * data[0]**3 * cos(data[0]) * sin(data[0]) * (cos(data[0]) * sin(data[0])**2 - 1)


def salustowicz_2d(data):
"""Salustowicz benchmark function.
r"""Salustowicz benchmark function.
.. list-table::
:widths: 10 50
Expand All @@ -57,6 +60,7 @@ def salustowicz_2d(data):
"""
return exp(-data[0]) * data[0]**3 * cos(data[0]) * sin(data[0]) * (cos(data[0]) * sin(data[0])**2 - 1) * (data[1] - 5)


def unwrapped_ball(data):
"""Unwrapped ball benchmark function.
Expand All @@ -71,6 +75,7 @@ def unwrapped_ball(data):
"""
return 10. / (5. + sum((d - 3)**2 for d in data))


def rational_polynomial(data):
"""Rational polynomial ball benchmark function.
Expand All @@ -85,6 +90,7 @@ def rational_polynomial(data):
"""
return 30. * (data[0] - 1) * (data[2] - 1) / (data[1]**2 * (data[0] - 10))


def sin_cos(data):
"""Sine cosine benchmark function.
Expand All @@ -99,6 +105,7 @@ def sin_cos(data):
"""
6 * sin(data[0]) * cos(data[1])


def ripple(data):
"""Ripple benchmark function.
Expand All @@ -113,6 +120,7 @@ def ripple(data):
"""
return (data[0] - 3) * (data[1] - 3) + 2 * sin((data[0] - 4) * (data[1] - 4))


def rational_polynomial2(data):
"""Rational polynomial benchmark function.
Expand Down
6 changes: 5 additions & 1 deletion deap/benchmarks/movingpeaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
except:
from collections import Sequence


def cone(individual, position, height, width):
"""The cone peak function to be used with scenario 2 and 3.
Expand All @@ -41,6 +42,7 @@ def cone(individual, position, height, width):
value += (x - p)**2
return height - width * math.sqrt(value)


def sphere(individual, position, height, width):
value = 0.0
for x, p in zip(individual, position):
Expand All @@ -58,6 +60,7 @@ def function1(individual, position, height, width):
value += (x - p)**2
return height / (1 + width * value)


class MovingPeaks:
"""The Moving Peaks Benchmark is a fitness function changing over time. It
consists of a number of peaks, changing in height, width and location. The
Expand Down Expand Up @@ -161,7 +164,6 @@ def __init__(self, dim, random=random, **kargs):
else:
self.peaks_height = [self.random.uniform(self.min_height, self.max_height) for _ in range(npeaks)]


if uniform_width != 0:
self.peaks_width = [uniform_width for _ in range(npeaks)]
else:
Expand Down Expand Up @@ -382,6 +384,7 @@ def changePeaks(self):
"width_severity": 0.5,
"period": 1000}


def diversity(population):
nind = len(population)
ndim = len(population[0])
Expand All @@ -391,6 +394,7 @@ def diversity(population):
d = [di / nind for di in d]
return math.sqrt(sum((di - xi)**2 for x in population for di, xi in zip(d, x)))


if __name__ == "__main__":
mpb = MovingPeaks(dim=2, npeaks=[1,1,10], number_severity=0.1)
print(mpb.maximums())
Expand Down
7 changes: 7 additions & 0 deletions deap/benchmarks/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
# fallback on python version
from ..tools._hypervolume import pyhv as hv


class translate(object):
"""Decorator for evaluation functions, it translates the objective
function by *vector* which should be the same length as the individual
Expand Down Expand Up @@ -61,6 +62,7 @@ def evaluate(individual):
"""
self.vector = vector


class rotate(object):
"""Decorator for evaluation functions, it rotates the objective function
by *matrix* which should be a valid orthogonal NxN rotation matrix, with N
Expand Down Expand Up @@ -114,6 +116,7 @@ def evaluate(individual):
"""
self.matrix = numpy.linalg.inv(matrix)


class noise(object):
"""Decorator for evaluation functions, it evaluates the objective function
and adds noise by calling the function(s) provided in the *noise*
Expand Down Expand Up @@ -168,6 +171,7 @@ def evaluate(individual):
except TypeError:
self.rand_funcs = repeat(noise)


class scale(object):
"""Decorator for evaluation functions, it scales the objective function by
*factor* which should be the same length as the individual size. When
Expand Down Expand Up @@ -209,6 +213,7 @@ def evaluate(individual):
# objective function
self.factor = tuple(1.0/f for f in factor)


class bound(object):
"""Decorator for crossover and mutation functions, it changes the
individuals after the modification is done to bring it back in the allowed
Expand Down Expand Up @@ -253,6 +258,7 @@ def __init__(self, bounds, type):
elif type == "clip":
self.bound = self._clip


def diversity(first_front, first, last):
"""Given a Pareto front `first_front` and the two extreme points of the
optimal Pareto front, this function returns a metric of the diversity
Expand All @@ -275,6 +281,7 @@ def diversity(first_front, first, last):
delta = (df + dl + di)/(df + dl + len(dt) * dm )
return delta


def convergence(first_front, optimal_front):
"""Given a Pareto front `first_front` and the optimal Pareto front,
this function returns a metric of convergence
Expand Down
2 changes: 2 additions & 0 deletions deap/creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ def __deepcopy__(self, memo):

def __reduce__(self):
return (self.__class__, (list(self),), self.__dict__)


class_replacers[array.array] = _array


Expand Down
5 changes: 5 additions & 0 deletions deap/tests/test_algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,23 @@ def setup_func_single_obj():
creator.create(FITCLSNAME, base.Fitness, weights=(-1.0,))
creator.create(INDCLSNAME, list, fitness=creator.__dict__[FITCLSNAME])


def setup_func_multi_obj():
creator.create(FITCLSNAME, base.Fitness, weights=(-1.0, -1.0))
creator.create(INDCLSNAME, list, fitness=creator.__dict__[FITCLSNAME])


def setup_func_multi_obj_numpy():
creator.create(FITCLSNAME, base.Fitness, weights=(-1.0, -1.0))
creator.create(INDCLSNAME, numpy.ndarray, fitness=creator.__dict__[FITCLSNAME])


def teardown_func():
# Messy way to remove a class from the creator
del creator.__dict__[FITCLSNAME]
del creator.__dict__[INDCLSNAME]


@with_setup(setup_func_single_obj, teardown_func)
def test_cma():
NDIM = 5
Expand All @@ -65,6 +69,7 @@ def test_cma():

assert best.fitness.values < (1e-8,), "CMA algorithm did not converged properly."


@with_setup(setup_func_multi_obj, teardown_func)
def test_nsga2():
NDIM = 5
Expand Down
4 changes: 4 additions & 0 deletions deap/tests/test_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@

CNAME = "CLASS_NAME"


def teardown_func():
creator.__dict__.pop(CNAME)


@with_setup(None, teardown_func)
def test_create():
creator.create(CNAME, list)
Expand All @@ -44,6 +46,7 @@ def test_attribute():

assert l.a == 1, "%s, expected %i" % (l.a, 1)


@with_setup(None, teardown_func)
def test_array():
creator.create(CNAME, array.array, typecode="i")
Expand All @@ -56,6 +59,7 @@ def test_array():
assert a == ta, "%s, expected %s" % (a, ta)
assert b == tb, "%s, expected %s" % (b, tb)


@skipIf(not numpy, "Cannot import Numpy numerical library")
@with_setup(None, teardown_func)
def test_numpy_nocopy():
Expand Down
4 changes: 1 addition & 3 deletions deap/tests/test_logbook.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import sys
import unittest

from deap import tools


class LogbookTest(unittest.TestCase):

def setUp(self):
Expand Down Expand Up @@ -37,8 +37,6 @@ def test_no_chapters(self):
print(self.logbook.stream)



if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(LogbookTest)
unittest.TextTestRunner(verbosity=2).run(suite)

1 change: 1 addition & 0 deletions deap/tests/test_mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from deap.tools.mutation import mutInversion


class MutationTest(unittest.TestCase):

def test_mutInverstion_size_zero_chromosome_returns_unchanged_chromosome_in_tuple(self):
Expand Down
3 changes: 2 additions & 1 deletion deap/tests/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
from deap import gp
from deap import tools


def func():
return "True"


class Pickling(unittest.TestCase):

def setUp(self):
Expand Down Expand Up @@ -131,7 +133,6 @@ def test_pickle_population(self):
self.assertEqual(pop[2], pop_l[2], "Unpickled individual list != pickled individual list")
self.assertEqual(pop[2].fitness, pop_l[2].fitness, "Unpickled individual fitness != pickled individual fitness")


# @unittest.skipIf(platform.python_implementation() == "PyPy", "PyPy support for pickling ndarrays (thus stats) is very unstable.")
def test_pickle_logbook(self):
stats = tools.Statistics()
Expand Down
Loading

0 comments on commit 8aa17a0

Please sign in to comment.