From bacf89e71cb25145b490926a16a6b0967d5b7824 Mon Sep 17 00:00:00 2001 From: Marc Otto Date: Mon, 23 May 2016 11:33:26 +0200 Subject: [PATCH 1/4] add parameter specific mutation rate for mutPolynomialBounded --- deap/tools/mutation.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/deap/tools/mutation.py b/deap/tools/mutation.py index ff30ba4b5..2c0152fb1 100644 --- a/deap/tools/mutation.py +++ b/deap/tools/mutation.py @@ -60,9 +60,15 @@ def mutPolynomialBounded(individual, eta, low, up, indpb): is the lower bound of the search space. :param up: A value or a :term:`python:sequence` of values that is the upper bound of the search space. + :param indpb: A value or a :term:`python:sequence` of values that + is the probability of mutation (per parameter). :returns: A tuple of one individual. """ size = len(individual) + if not isinstance(indpb, Sequence): + indpb = repeat(indpb, size) + elif len(indpb) < size: + raise IndexError("indpb must be at least the size of individual: %d < %d" % (len(indpb), size)) if not isinstance(low, Sequence): low = repeat(low, size) elif len(low) < size: @@ -73,7 +79,7 @@ def mutPolynomialBounded(individual, eta, low, up, indpb): raise IndexError("up must be at least the size of individual: %d < %d" % (len(up), size)) for i, xl, xu in zip(xrange(size), low, up): - if random.random() <= indpb: + if random.random() <= indpb[i]: x = individual[i] delta_1 = (x - xl) / (xu - xl) delta_2 = (xu - x) / (xu - xl) From de29b0686104589700825acfb52f6943243fe27e Mon Sep 17 00:00:00 2001 From: Marc Otto Date: Mon, 23 May 2016 14:32:27 +0200 Subject: [PATCH 2/4] fix mutation rate application --- deap/tools/mutation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/deap/tools/mutation.py b/deap/tools/mutation.py index 2c0152fb1..257e03b95 100644 --- a/deap/tools/mutation.py +++ b/deap/tools/mutation.py @@ -77,9 +77,9 @@ def mutPolynomialBounded(individual, eta, low, up, indpb): up = repeat(up, size) elif len(up) < size: raise IndexError("up must be at least the size of individual: %d < %d" % (len(up), size)) - - for i, xl, xu in zip(xrange(size), low, up): - if random.random() <= indpb[i]: + + for i, xl, xu, mp in zip(xrange(size), low, up, indpb): + if random.random() <= mp: x = individual[i] delta_1 = (x - xl) / (xu - xl) delta_2 = (xu - x) / (xu - xl) From 2784e19ab768800ecc38091662cfef78344c9dba Mon Sep 17 00:00:00 2001 From: Marc Otto Date: Mon, 13 Sep 2021 15:48:35 +0200 Subject: [PATCH 3/4] python3 update --- deap/base.py | 11 +++++------ deap/creator.py | 4 ++-- deap/tools/crossover.py | 2 +- deap/tools/emo.py | 6 +++--- deap/tools/mutation.py | 2 +- 5 files changed, 12 insertions(+), 13 deletions(-) diff --git a/deap/base.py b/deap/base.py index 57d6a8d72..dc6998cb1 100644 --- a/deap/base.py +++ b/deap/base.py @@ -190,12 +190,11 @@ def setValues(self, values): self.wvalues = tuple(map(mul, values, self.weights)) except TypeError: _, _, traceback = sys.exc_info() - raise TypeError, ("Both weights and assigned values must be a " - "sequence of numbers when assigning to values of " - "%r. Currently assigning value(s) %r of %r to a " - "fitness with weights %s." - % (self.__class__, values, type(values), - self.weights)), traceback + raise TypeError("Both weights and assigned values must be a " + "sequence of numbers when assigning to values of " + "%r. Currently assigning value(s) %r of %r to a " + "fitness with weights %s." + % (self.__class__, values, type(values), self.weights)) def delValues(self): self.wvalues = () diff --git a/deap/creator.py b/deap/creator.py index 9b0f61aab..06e00e8a7 100644 --- a/deap/creator.py +++ b/deap/creator.py @@ -142,7 +142,7 @@ def __init__(self): dict_inst = {} dict_cls = {} - for obj_name, obj in kargs.iteritems(): + for obj_name, obj in kargs.items(): if isinstance(obj, type): dict_inst[obj_name] = obj else: @@ -161,7 +161,7 @@ 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.iteritems(): + 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) diff --git a/deap/tools/crossover.py b/deap/tools/crossover.py index e64d02deb..5ea44888f 100644 --- a/deap/tools/crossover.py +++ b/deap/tools/crossover.py @@ -321,7 +321,7 @@ def cxSimulatedBinaryBounded(ind1, ind2, eta, low, up): elif len(up) < size: raise IndexError("up must be at least the size of the shorter individual: %d < %d" % (len(up), size)) - for i, xl, xu in zip(xrange(size), low, up): + for i, xl, xu in zip(range(size), low, up): if random.random() <= 0.5: # This epsilon should probably be changed for 0 since # floating point arithmetic in Python is safer diff --git a/deap/tools/emo.py b/deap/tools/emo.py index 394dcdfa1..7b2058e66 100644 --- a/deap/tools/emo.py +++ b/deap/tools/emo.py @@ -74,7 +74,7 @@ def sortNondominated(individuals, k, first_front_only=False): map_fit_ind = defaultdict(list) for ind in individuals: map_fit_ind[ind.fitness].append(ind) - fits = map_fit_ind.keys() + fits = list(map_fit_ind.keys()) current_front = [] next_front = [] @@ -129,7 +129,7 @@ def assignCrowdingDist(individuals): nobj = len(individuals[0].fitness.values) - for i in xrange(nobj): + for i in range(nobj): crowd.sort(key=lambda element: element[0][i]) distances[crowd[0][1]] = float("inf") distances[crowd[-1][1]] = float("inf") @@ -186,7 +186,7 @@ def tourn(ind1, ind2): individuals_2 = random.sample(individuals, len(individuals)) chosen = [] - for i in xrange(0, k, 4): + for i in range(0, k, 4): chosen.append(tourn(individuals_1[i], individuals_1[i+1])) chosen.append(tourn(individuals_1[i+2], individuals_1[i+3])) chosen.append(tourn(individuals_2[i], individuals_2[i+1])) diff --git a/deap/tools/mutation.py b/deap/tools/mutation.py index 257e03b95..383c58fae 100644 --- a/deap/tools/mutation.py +++ b/deap/tools/mutation.py @@ -78,7 +78,7 @@ def mutPolynomialBounded(individual, eta, low, up, indpb): elif len(up) < size: raise IndexError("up must be at least the size of individual: %d < %d" % (len(up), size)) - for i, xl, xu, mp in zip(xrange(size), low, up, indpb): + for i, xl, xu, mp in zip(range(size), low, up, indpb): if random.random() <= mp: x = individual[i] delta_1 = (x - xl) / (xu - xl) From e46b22f7c30a908e213cb502d0ae0917abb02d65 Mon Sep 17 00:00:00 2001 From: Marc Otto Date: Fri, 11 Feb 2022 15:32:55 +0100 Subject: [PATCH 4/4] add result of 2to3 conversion (see https://stackoverflow.com/a/69100830) --- deap/algorithms.py | 22 +++++----- deap/benchmarks/__init__.py | 6 +-- deap/benchmarks/binary.py | 22 +++++----- deap/benchmarks/movingpeaks.py | 4 +- deap/benchmarks/tools.py | 2 +- deap/cma.py | 6 +-- deap/creator.py | 4 +- deap/gp.py | 34 +++++++------- deap/tests/test_benchmarks.py | 4 +- deap/tests/test_init.py | 2 +- deap/tests/test_logbook.py | 10 ++--- deap/tools/_hypervolume/pyhv.py | 18 ++++---- deap/tools/constraint.py | 4 +- deap/tools/crossover.py | 16 +++---- deap/tools/emo.py | 44 +++++++++---------- deap/tools/indicator.py | 2 +- deap/tools/init.py | 6 +-- deap/tools/migration.py | 10 ++--- deap/tools/mutation.py | 14 +++--- deap/tools/selection.py | 30 ++++++------- deap/tools/support.py | 30 ++++++------- doc/code/benchmarks/ackley.py | 2 +- doc/code/benchmarks/bohachevsky.py | 2 +- doc/code/benchmarks/griewank.py | 2 +- doc/code/benchmarks/h1.py | 2 +- doc/code/benchmarks/himmelblau.py | 2 +- doc/code/benchmarks/movingsc1.py | 2 +- doc/code/benchmarks/rastrigin.py | 2 +- doc/code/benchmarks/rosenbrock.py | 2 +- doc/code/benchmarks/schaffer.py | 2 +- doc/code/benchmarks/schwefel.py | 2 +- doc/code/benchmarks/shekel.py | 2 +- doc/code/tutorials/part_1/1_where_to_start.py | 6 +-- .../tutorials/part_2/2_2_2_permutation.py | 2 +- doc/code/tutorials/part_2/2_2_5_particle.py | 4 +- doc/code/tutorials/part_2/2_3_3_swarm.py | 4 +- doc/code/tutorials/part_2/2_3_4_demes.py | 2 +- .../tutorials/part_3/3_6_2_tool_decoration.py | 2 +- .../tutorials/part_3/3_6_using_the_toolbox.py | 2 +- doc/code/tutorials/part_3/3_7_variations.py | 2 +- doc/code/tutorials/part_3/3_next_step.py | 14 +++--- doc/code/tutorials/part_3/logbook.py | 4 +- doc/code/tutorials/part_3/multistats.py | 2 +- doc/code/tutorials/part_3/stats.py | 2 +- .../tutorials/part_4/4_4_Using_Cpp_NSGA.py | 22 +++++----- .../part_4/4_5_home_made_eval_func.py | 30 ++++++------- doc/code/tutorials/part_4/sortingnetwork.py | 16 +++---- doc/conf.py | 8 ++-- examples/bbob.py | 8 ++-- examples/coev/coop_adapt.py | 4 +- examples/coev/coop_evol.py | 8 ++-- examples/coev/coop_gen.py | 4 +- examples/coev/coop_niche.py | 4 +- examples/coev/hillis.py | 8 ++-- examples/coev/symbreg.py | 8 ++-- examples/de/basic.py | 6 +-- examples/de/dynamic.py | 6 +-- examples/de/sphere.py | 10 ++--- examples/es/cma_bipop.py | 6 +-- examples/es/cma_mo.py | 8 ++-- examples/es/cma_plotting.py | 2 +- examples/es/onefifth.py | 2 +- examples/ga/evosn.py | 8 ++-- examples/ga/knn.py | 8 ++-- examples/ga/mo_rhv.py | 8 ++-- examples/ga/nqueens.py | 2 +- examples/ga/nsga2.py | 6 +-- examples/ga/nsga3.py | 6 +-- examples/ga/onemax.py | 18 ++++---- examples/ga/onemax_island.py | 6 +-- examples/ga/onemax_multidemic.py | 4 +- examples/ga/tsp.py | 2 +- examples/ga/xkcd.py | 4 +- examples/gp/adf_symbreg.py | 6 +-- examples/pso/basic.py | 8 ++-- examples/pso/basic_numpy.py | 2 +- examples/pso/multiswarm.py | 22 +++++----- examples/pso/speciation.py | 18 ++++---- setup.py | 12 ++--- 79 files changed, 329 insertions(+), 329 deletions(-) diff --git a/deap/algorithms.py b/deap/algorithms.py index ef1d9e799..58a61d502 100644 --- a/deap/algorithms.py +++ b/deap/algorithms.py @@ -27,7 +27,7 @@ import random -import tools +from . import tools def varAnd(population, toolbox, cxpb, mutpb): @@ -157,7 +157,7 @@ def eaSimple(population, toolbox, cxpb, mutpb, ngen, stats=None, record = stats.compile(population) if stats else {} logbook.record(gen=0, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) # Begin the generational process for gen in range(1, ngen + 1): @@ -184,7 +184,7 @@ def eaSimple(population, toolbox, cxpb, mutpb, ngen, stats=None, record = stats.compile(population) if stats else {} logbook.record(gen=gen, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) return population, logbook @@ -227,10 +227,10 @@ def varOr(population, toolbox, lambda_, cxpb, mutpb): "or equal to 1.0.") offspring = [] - for _ in xrange(lambda_): + for _ in range(lambda_): op_choice = random.random() if op_choice < cxpb: # Apply crossover - ind1, ind2 = map(toolbox.clone, random.sample(population, 2)) + ind1, ind2 = list(map(toolbox.clone, random.sample(population, 2))) ind1, ind2 = toolbox.mate(ind1, ind2) del ind1.fitness.values offspring.append(ind1) @@ -308,7 +308,7 @@ def eaMuPlusLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, record = stats.compile(population) if stats is not None else {} logbook.record(gen=0, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) # Begin the generational process for gen in range(1, ngen + 1): @@ -332,7 +332,7 @@ def eaMuPlusLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, record = stats.compile(population) if stats is not None else {} logbook.record(gen=gen, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) return population, logbook @@ -409,7 +409,7 @@ def eaMuCommaLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, record = stats.compile(population) if stats is not None else {} logbook.record(gen=0, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) # Begin the generational process for gen in range(1, ngen + 1): @@ -433,7 +433,7 @@ def eaMuCommaLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, record = stats.compile(population) if stats is not None else {} logbook.record(gen=gen, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) return population, logbook @@ -481,7 +481,7 @@ def eaGenerateUpdate(toolbox, ngen, halloffame=None, stats=None, logbook = tools.Logbook() logbook.header = ['gen', 'nevals'] + (stats.fields if stats else []) - for gen in xrange(ngen): + for gen in range(ngen): # Generate a new population population = toolbox.generate() # Evaluate the individuals @@ -498,6 +498,6 @@ def eaGenerateUpdate(toolbox, ngen, halloffame=None, stats=None, record = stats.compile(population) if stats is not None else {} logbook.record(gen=gen, nevals=len(population), **record) if verbose: - print logbook.stream + print(logbook.stream) return population, logbook diff --git a/deap/benchmarks/__init__.py b/deap/benchmarks/__init__.py index 48a1bf2b6..a6dcc0f38 100644 --- a/deap/benchmarks/__init__.py +++ b/deap/benchmarks/__init__.py @@ -489,7 +489,7 @@ def dtlz1(individual, obj): """ g = 100 * (len(individual[obj-1:]) + sum((xi-0.5)**2 - cos(20*pi*(xi-0.5)) for xi in individual[obj-1:])) f = [0.5 * reduce(mul, individual[:obj-1], 1) * (1 + g)] - f.extend(0.5 * reduce(mul, individual[:m], 1) * (1 - individual[m]) * (1 + g) for m in reversed(xrange(obj-1))) + f.extend(0.5 * reduce(mul, individual[:m], 1) * (1 - individual[m]) * (1 + g) for m in reversed(range(obj-1))) return f def dtlz2(individual, obj): @@ -588,7 +588,7 @@ def dtlz5(ind, n_objs): theta = lambda x: pi / (4.0 * (1 + gval)) * (1 + 2 * gval * x) fit = [(1 + gval) * cos(pi / 2.0 * ind[0]) * reduce(lambda x,y: x*y, [cos(theta(a)) for a in ind[1:]])] - for m in reversed(range(1, n_objs)): + for m in reversed(list(range(1, n_objs))): if m == 1: fit.append((1 + gval) * sin(pi / 2.0 * ind[0])) else: @@ -608,7 +608,7 @@ def dtlz6(ind, n_objs): fit = [(1 + gval) * cos(pi / 2.0 * ind[0]) * reduce(lambda x,y: x*y, [cos(theta(a)) for a in ind[1:]])] - for m in reversed(range(1, n_objs)): + for m in reversed(list(range(1, n_objs))): if m == 1: fit.append((1 + gval) * sin(pi / 2.0 * ind[0])) else: diff --git a/deap/benchmarks/binary.py b/deap/benchmarks/binary.py index 2b777ef81..3fc5097c2 100644 --- a/deap/benchmarks/binary.py +++ b/deap/benchmarks/binary.py @@ -13,7 +13,7 @@ # You should have received a copy of the GNU Lesser General Public # License along with DEAP. If not, see . -from __future__ import division + from functools import wraps import math @@ -29,7 +29,7 @@ def wrapped_function(individual, *args, **kargs): # User must take care to make nelem an integer. nelem = len(individual)//nbits decoded = [0] * nelem - for i in xrange(nelem): + for i in range(nelem): gene = int("".join(map(str, individual[i*nbits:i*nbits+nbits])), 2) @@ -68,10 +68,10 @@ def chuang_f1(individual): """ total = 0 if individual[-1] == 0: - for i in xrange(0, len(individual)-1, 4): + for i in range(0, len(individual)-1, 4): total += inv_trap(individual[i:i+4]) else: - for i in xrange(0, len(individual)-1, 4): + for i in range(0, len(individual)-1, 4): total += trap(individual[i:i+4]) return total, @@ -85,16 +85,16 @@ def chuang_f2(individual): """ total = 0 if individual[-2] == 0 and individual[-1] == 0: - for i in xrange(0, len(individual)-2, 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 xrange(0, len(individual)-2, 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 xrange(0, len(individual)-2, 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 xrange(0, len(individual)-2, 8): + for i in range(0, len(individual)-2, 8): total += trap(individual[i:i+4]) + trap(individual[i+4:i+8]) return total, @@ -108,10 +108,10 @@ def chuang_f3(individual): """ total = 0 if individual[-1] == 0: - for i in xrange(0, len(individual)-1, 4): + for i in range(0, len(individual)-1, 4): total += inv_trap(individual[i:i+4]) else: - for i in xrange(2, len(individual)-3, 4): + for i in range(2, len(individual)-3, 4): total += inv_trap(individual[i:i+4]) total += trap(individual[-2:]+individual[:2]) return total, @@ -125,7 +125,7 @@ def royal_road1(individual, order): nelem = len(individual) // order max_value = int(2**order - 1) total = 0 - for i in xrange(nelem): + for i in range(nelem): value = int("".join(map(str, individual[i*order:i*order+order])), 2) total += int(order) * int(value/max_value) return total, diff --git a/deap/benchmarks/movingpeaks.py b/deap/benchmarks/movingpeaks.py index 5255ae73f..b90a558ed 100644 --- a/deap/benchmarks/movingpeaks.py +++ b/deap/benchmarks/movingpeaks.py @@ -393,6 +393,6 @@ def diversity(population): if __name__ == "__main__": mpb = MovingPeaks(dim=2, npeaks=[1,1,10], number_severity=0.1) - print mpb.maximums() + print(mpb.maximums()) mpb.changePeaks() - print mpb.maximums() + print(mpb.maximums()) diff --git a/deap/benchmarks/tools.py b/deap/benchmarks/tools.py index ee71adaf1..bc3043e2f 100644 --- a/deap/benchmarks/tools.py +++ b/deap/benchmarks/tools.py @@ -287,7 +287,7 @@ def convergence(first_front, optimal_front): distances.append(float("inf")) for opt_ind in optimal_front: dist = 0. - for i in xrange(len(opt_ind)): + for i in range(len(opt_ind)): dist += (ind.fitness.values[i] - opt_ind[i])**2 if dist < distances[-1]: distances[-1] = dist diff --git a/deap/cma.py b/deap/cma.py index 5efd41119..30707294b 100644 --- a/deap/cma.py +++ b/deap/cma.py @@ -24,7 +24,7 @@ from math import sqrt, log, exp import numpy -import tools +from . import tools class Strategy(object): @@ -118,7 +118,7 @@ def generate(self, ind_init): """ arz = numpy.random.standard_normal((self.lambda_, self.dim)) arz = self.centroid + self.sigma * numpy.dot(arz, self.BD.T) - return map(ind_init, arz) + return list(map(ind_init, arz)) def update(self, population): """Update the current covariance matrix strategy from the @@ -286,7 +286,7 @@ def generate(self, ind_init): # self.y = numpy.dot(self.A, numpy.random.standard_normal(self.dim)) arz = numpy.random.standard_normal((self.lambda_, self.dim)) arz = self.parent + self.sigma * numpy.dot(arz, self.A.T) - return map(ind_init, arz) + return list(map(ind_init, arz)) def update(self, population): """Update the current covariance matrix strategy from the diff --git a/deap/creator.py b/deap/creator.py index 06e00e8a7..51c0f53d9 100644 --- a/deap/creator.py +++ b/deap/creator.py @@ -142,7 +142,7 @@ def __init__(self): dict_inst = {} dict_cls = {} - for obj_name, obj in kargs.items(): + for obj_name, obj in list(kargs.items()): if isinstance(obj, type): dict_inst[obj_name] = obj else: @@ -161,7 +161,7 @@ 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(): + for obj_name, obj in list(dict_inst.items()): setattr(self, obj_name, obj()) if base.__init__ is not object.__init__: base.__init__(self, *args, **kargs) diff --git a/deap/gp.py b/deap/gp.py index f52fa7575..50a519f06 100644 --- a/deap/gp.py +++ b/deap/gp.py @@ -31,7 +31,7 @@ from inspect import isclass from operator import eq, lt -import tools # Needed by HARM-GP +from . import tools # Needed by HARM-GP ###################################### # GP Data structure # @@ -199,7 +199,7 @@ def __init__(self, name, args, ret): self.arity = len(args) self.args = args self.ret = ret - args = ", ".join(map("{{{0}}}".format, range(self.arity))) + args = ", ".join(map("{{{0}}}".format, list(range(self.arity)))) self.seq = "{name}({args})".format(name=self.name, args=args) def format(self, *args): @@ -300,7 +300,7 @@ def _add(self, prim): def addType(dict_, ret_type): if ret_type not in dict_: new_list = [] - for type_, list_ in dict_.items(): + for type_, list_ in list(dict_.items()): if issubclass(type_, ret_type): for item in list_: if item not in new_list: @@ -480,11 +480,11 @@ def compile(expr, pset): return eval(code, pset.context, {}) except MemoryError: _, _, traceback = sys.exc_info() - raise MemoryError, ("DEAP : Error in tree evaluation :" + raise MemoryError("DEAP : Error in tree evaluation :" " Python cannot evaluate a tree higher than 90. " "To avoid this problem, you should use bloat control on your " "operators. See the DEAP documentation for more information. " - "DEAP will now abort."), traceback + "DEAP will now abort.").with_traceback(traceback) def compileADF(expr, psets): @@ -506,7 +506,7 @@ def compileADF(expr, psets): """ adfdict = {} func = None - for pset, subexpr in reversed(zip(psets, expr)): + for pset, subexpr in reversed(list(zip(psets, expr))): pset.context.update(adfdict) func = compile(subexpr, pset) adfdict.update({pset.name: func}) @@ -618,9 +618,9 @@ def generate(pset, min_, max_, condition, type_=None): term = random.choice(pset.terminals[type_]) except IndexError: _, _, traceback = sys.exc_info() - raise IndexError, "The gp.generate function tried to add " \ + raise IndexError("The gp.generate function tried to add " \ "a terminal of type '%s', but there is " \ - "none available." % (type_,), traceback + "none available." % (type_,)).with_traceback(traceback) if isclass(term): term = term() expr.append(term) @@ -629,9 +629,9 @@ def generate(pset, min_, max_, condition, type_=None): prim = random.choice(pset.primitives[type_]) except IndexError: _, _, traceback = sys.exc_info() - raise IndexError, "The gp.generate function tried to add " \ + raise IndexError("The gp.generate function tried to add " \ "a primitive of type '%s', but there is " \ - "none available." % (type_,), traceback + "none available." % (type_,)).with_traceback(traceback) expr.append(prim) for arg in reversed(prim.args): stack.append((depth + 1, arg)) @@ -659,8 +659,8 @@ def cxOnePoint(ind1, ind2): types2 = defaultdict(list) if ind1.root.ret == __type__: # Not STGP optimization - types1[__type__] = xrange(1, len(ind1)) - types2[__type__] = xrange(1, len(ind2)) + types1[__type__] = range(1, len(ind1)) + types2[__type__] = range(1, len(ind2)) common_types = [__type__] else: for idx, node in enumerate(ind1[1:], 1): @@ -1014,8 +1014,8 @@ def _genpop(n, pickfrom=[], acceptfunc=lambda s: True, producesizes=False): opRandom = random.random() if opRandom < cxpb: # Crossover - aspirant1, aspirant2 = toolbox.mate(*map(toolbox.clone, - toolbox.select(population, 2))) + aspirant1, aspirant2 = toolbox.mate(*list(map(toolbox.clone, + toolbox.select(population, 2)))) del aspirant1.fitness.values, aspirant2.fitness.values if acceptfunc(len(aspirant1)): producedpop.append(aspirant1) @@ -1063,7 +1063,7 @@ def halflifefunc(x): record = stats.compile(population) if stats else {} logbook.record(gen=0, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) # Begin the generational process for gen in range(1, ngen + 1): @@ -1130,7 +1130,7 @@ def acceptfunc(s): record = stats.compile(population) if stats else {} logbook.record(gen=gen, nevals=len(invalid_ind), **record) if verbose: - print logbook.stream + print(logbook.stream) return population, logbook @@ -1191,7 +1191,7 @@ def graph(expr): `_ as the nodes might be plotted out of order when using `NetworX `_. """ - nodes = range(len(expr)) + nodes = list(range(len(expr))) edges = list() labels = dict() diff --git a/deap/tests/test_benchmarks.py b/deap/tests/test_benchmarks.py index 83ec92419..23468cc3e 100644 --- a/deap/tests/test_benchmarks.py +++ b/deap/tests/test_benchmarks.py @@ -32,7 +32,7 @@ def test_bin2float(self): full_individual = creator.Individual([1] * 10) two_individiual = creator.Individual(8*[0] + [1, 0]) population = [zero_individual, full_individual, two_individiual] - fitnesses = map(self.toolbox.evaluate, population) + fitnesses = list(map(self.toolbox.evaluate, population)) for ind, fit in zip(population, fitnesses): ind.fitness.values = fit assert population[0].fitness.values == (0.0, ) @@ -44,7 +44,7 @@ def test_bin2float(self): wrong_population = [wrong_size_individual] # It is up the user to make sure that bin2float gets an individual with # an adequate length; no exceptions are raised. - fitnesses = map(self.toolbox.evaluate, wrong_population) + fitnesses = list(map(self.toolbox.evaluate, wrong_population)) for ind, fit in zip(wrong_population, fitnesses): # In python 2.7 operator.mul works in a different way than in # python3. Thus an error occurs in python2.7 but an assignment is diff --git a/deap/tests/test_init.py b/deap/tests/test_init.py index c3117bd86..909000042 100644 --- a/deap/tests/test_init.py +++ b/deap/tests/test_init.py @@ -8,6 +8,6 @@ class LogbookTest(unittest.TestCase): def test_statistics_compile(self): l = 10 - gen_idx = partial(random.sample, range(l), l) + gen_idx = partial(random.sample, list(range(l)), l) i = tools.initIterate(list, gen_idx) self.assertSetEqual(set(i), set(range(l))) diff --git a/deap/tests/test_logbook.py b/deap/tests/test_logbook.py index 7a7639ebe..cfcdfff0f 100644 --- a/deap/tests/test_logbook.py +++ b/deap/tests/test_logbook.py @@ -7,7 +7,7 @@ class LogbookTest(unittest.TestCase): def setUp(self): self.logbook = tools.Logbook() - print + print() def test_multi_chapters(self): self.logbook.record(gen=0, evals=100, fitness={'obj 1' : {'avg' : 1.0, 'max' : 10}, @@ -18,23 +18,23 @@ def test_multi_chapters(self): 'obj 2' : {'avg' : 1.0, 'max' : 10}}, length={'avg' : 1.0, 'max' : 30}, test={'avg' : 1.0, 'max' : 20}) - print(self.logbook.stream) + print((self.logbook.stream)) def test_one_chapter(self): self.logbook.record(gen=0, evals=100, fitness={'avg' : 1.0, 'max' : 10}) self.logbook.record(gen=0, evals=100, fitness={'avg' : 1.0, 'max' : 10}) - print(self.logbook.stream) + print((self.logbook.stream)) def test_one_big_chapter(self): self.logbook.record(gen=0, evals=100, fitness={'obj 1' : {'avg' : 1.0, 'max' : 10}, 'obj 2' : {'avg' : 1.0, 'max' : 10}}) self.logbook.record(gen=0, evals=100, fitness={'obj 1' : {'avg' : 1.0, 'max' : 10}, 'obj 2' : {'avg' : 1.0, 'max' : 10}}) - print(self.logbook.stream) + print((self.logbook.stream)) def test_no_chapters(self): self.logbook.record(gen=0, evals=100, **{'avg' : 1.0, 'max' : 10}) self.logbook.record(gen=0, evals=100, **{'avg' : 1.0, 'max' : 10}) - print(self.logbook.stream) + print((self.logbook.stream)) diff --git a/deap/tools/_hypervolume/pyhv.py b/deap/tools/_hypervolume/pyhv.py index 508dc8d21..063db420d 100644 --- a/deap/tools/_hypervolume/pyhv.py +++ b/deap/tools/_hypervolume/pyhv.py @@ -64,7 +64,7 @@ def compute(self, front): """ def weaklyDominates(point, other): - for i in xrange(len(point)): + for i in range(len(point)): if point[i] > other[i]: return False return True @@ -152,7 +152,7 @@ def hvRecursive(self, dimIndex, length, bounds): hvol = qPrevDimIndex.volume[dimIndex] + qPrevDimIndex.area[dimIndex] * (qCargo[dimIndex] - qPrevDimIndex.cargo[dimIndex]) else: qArea[0] = 1 - qArea[1:dimIndex+1] = [qArea[i] * -qCargo[i] for i in xrange(dimIndex)] + qArea[1:dimIndex+1] = [qArea[i] * -qCargo[i] for i in range(dimIndex)] q.volume[dimIndex] = hvol if q.ignore >= dimIndex: qArea[dimIndex] = qPrevDimIndex.area[dimIndex] @@ -184,7 +184,7 @@ def preProcess(self, front): dimensions = len(self.referencePoint) nodeList = _MultiList(dimensions) nodes = [_MultiList.Node(dimensions, point) for point in front] - for i in xrange(dimensions): + for i in range(dimensions): self.sortByDimension(nodes, i) nodeList.extend(nodes, i) self.list = nodeList @@ -239,7 +239,7 @@ def __init__(self, numberLists): def __str__(self): strings = [] - for i in xrange(self.numberLists): + for i in range(self.numberLists): currentList = [] node = self.sentinel.next[i] while node != self.sentinel: @@ -292,7 +292,7 @@ def extend(self, nodes, index): def remove(self, node, index, bounds): """Removes and returns 'node' from all lists in [0, 'index'[.""" - for i in xrange(index): + for i in range(index): predecessor = node.prev[i] successor = node.next[i] predecessor.next[i] = successor @@ -309,7 +309,7 @@ def reinsert(self, node, index, bounds): nodes of the node that is reinserted are in the list. """ - for i in xrange(index): + for i in range(index): node.prev[i].next[i] = node node.next[i].prev[i] = node if bounds[i] > node.cargo[i]: @@ -329,8 +329,8 @@ def reinsert(self, node, index, bounds): pointset = [(a, a) for a in numpy.arange(1, 0, -0.01)] ref = numpy.array([2, 2]) - print("Python version: %f" % hypervolume(pointset, ref)) + print(("Python version: %f" % hypervolume(pointset, ref))) if hv: - print("C version: %f" % hv.hypervolume(pointset, ref)) - print("Approximated: %f" % hypervolume_approximation(pointset, ref)) + print(("C version: %f" % hv.hypervolume(pointset, ref))) + print(("Approximated: %f" % hypervolume_approximation(pointset, ref))) diff --git a/deap/tools/constraint.py b/deap/tools/constraint.py index 5617aff35..e7cdcc58a 100644 --- a/deap/tools/constraint.py +++ b/deap/tools/constraint.py @@ -172,6 +172,6 @@ def valid(individual): toolbox.decorate("evaluate", ClosestValidPenalty(valid, closest_feasible, 1.0e-6, distance)) ind1 = creator.Individual((-5.6468535666e-01,2.2483050478e+00,-1.1087909644e+00,-1.2710112861e-01,1.1682438733e+00,-1.3642007438e+00,-2.1916417835e-01,-5.9137308999e-01,-1.0870160336e+00,6.0515070232e-01,2.1532075914e+00,-2.6164718271e-01,1.5244071578e+00,-1.0324305612e+00,1.2858152343e+00,-1.2584683962e+00,1.2054392372e+00,-1.7429571973e+00,-1.3517256013e-01,-2.6493429355e+00,-1.3051320798e-01,2.2641961090e+00,-2.5027232340e+00,-1.2844874148e+00,1.9955852925e+00,-1.2942218834e+00,3.1340109155e+00,1.6440111097e+00,-1.7750105857e+00,7.7610242710e-01)) - print(toolbox.evaluate(ind1)) - print("Individuals is valid: %s" % ("True" if valid(ind1) else "False")) + print((toolbox.evaluate(ind1))) + print(("Individuals is valid: %s" % ("True" if valid(ind1) else "False"))) diff --git a/deap/tools/crossover.py b/deap/tools/crossover.py index 5ea44888f..9dee7c11f 100644 --- a/deap/tools/crossover.py +++ b/deap/tools/crossover.py @@ -1,4 +1,4 @@ -from __future__ import division + import random import warnings @@ -84,7 +84,7 @@ def cxUniform(ind1, ind2, indpb): :mod:`random` module. """ size = min(len(ind1), len(ind2)) - for i in xrange(size): + for i in range(size): if random.random() < indpb: ind1[i], ind2[i] = ind2[i], ind1[i] @@ -115,7 +115,7 @@ def cxPartialyMatched(ind1, ind2): p1, p2 = [0] * size, [0] * size # Initialize the position of each indices in the individuals - for i in xrange(size): + for i in range(size): p1[ind1[i]] = i p2[ind2[i]] = i # Choose crossover points @@ -127,7 +127,7 @@ def cxPartialyMatched(ind1, ind2): cxpoint1, cxpoint2 = cxpoint2, cxpoint1 # Apply crossover between cx points - for i in xrange(cxpoint1, cxpoint2): + for i in range(cxpoint1, cxpoint2): # Keep track of the selected values temp1 = ind1[i] temp2 = ind2[i] @@ -166,11 +166,11 @@ def cxUniformPartialyMatched(ind1, ind2, indpb): p1, p2 = [0] * size, [0] * size # Initialize the position of each indices in the individuals - for i in xrange(size): + for i in range(size): p1[ind1[i]] = i p2[ind2[i]] = i - for i in xrange(size): + for i in range(size): if random.random() < indpb: # Keep track of the selected values temp1 = ind1[i] @@ -209,7 +209,7 @@ def cxOrdered(ind1, ind2): optimization and machine learning. Addison Wesley, 1989 """ size = min(len(ind1), len(ind2)) - a, b = random.sample(xrange(size), 2) + a, b = random.sample(range(size), 2) if a > b: a, b = b, a @@ -321,7 +321,7 @@ def cxSimulatedBinaryBounded(ind1, ind2, eta, low, up): elif len(up) < size: raise IndexError("up must be at least the size of the shorter individual: %d < %d" % (len(up), size)) - for i, xl, xu in zip(range(size), low, up): + for i, xl, xu in zip(list(range(size)), low, up): if random.random() <= 0.5: # This epsilon should probably be changed for 0 since # floating point arithmetic in Python is safer diff --git a/deap/tools/emo.py b/deap/tools/emo.py index 7b2058e66..a48086c9f 100644 --- a/deap/tools/emo.py +++ b/deap/tools/emo.py @@ -1,4 +1,4 @@ -from __future__ import division + import bisect from collections import defaultdict, namedtuple from itertools import chain @@ -250,7 +250,7 @@ def sortLogNondominated(individuals, k, first_front_only=False): #Launch the sorting algorithm obj = len(individuals[0].fitness.wvalues)-1 - fitnesses = unique_fits.keys() + fitnesses = list(unique_fits.keys()) front = dict.fromkeys(fitnesses, 0) # Sort the fitnesses lexicographically. @@ -286,7 +286,7 @@ def sortNDHelperA(fitnesses, obj, front): front[s2] = max(front[s2], front[s1] + 1) elif obj == 1: sweepA(fitnesses, front) - elif len(frozenset(map(itemgetter(obj), fitnesses))) == 1: + elif len(frozenset(list(map(itemgetter(obj), fitnesses)))) == 1: #All individuals for objective M are equal: go to objective M-1 sortNDHelperA(fitnesses, obj-1, front) else: @@ -620,7 +620,7 @@ def associate_to_niche(fitnesses, reference_points, best_point, intercepts): # Retrieve min distance niche index niches = numpy.argmin(distances, axis=1) - distances = distances[range(niches.shape[0]), niches] + distances = distances[list(range(niches.shape[0])), niches] return niches, distances @@ -710,7 +710,7 @@ def selSPEA2(individuals, k): K = math.sqrt(N) strength_fits = [0] * N fits = [0] * N - dominating_inds = [list() for i in xrange(N)] + dominating_inds = [list() for i in range(N)] for i, ind_i in enumerate(individuals): for j, ind_j in enumerate(individuals[i+1:], i+1): @@ -721,19 +721,19 @@ def selSPEA2(individuals, k): strength_fits[j] += 1 dominating_inds[i].append(j) - for i in xrange(N): + for i in range(N): for j in dominating_inds[i]: fits[i] += strength_fits[j] # Choose all non-dominated individuals - chosen_indices = [i for i in xrange(N) if fits[i] < 1] + chosen_indices = [i for i in range(N) if fits[i] < 1] if len(chosen_indices) < k: # The archive is too small - for i in xrange(N): + for i in range(N): distances = [0.0] * N - for j in xrange(i + 1, N): + for j in range(i + 1, N): dist = 0.0 - for l in xrange(L): + for l in range(L): val = individuals[i].fitness.values[l] - \ individuals[j].fitness.values[l] dist += val * val @@ -742,7 +742,7 @@ def selSPEA2(individuals, k): density = 1.0 / (kth_dist + 2.0) fits[i] += density - next_indices = [(fits[i], i) for i in xrange(N) + next_indices = [(fits[i], i) for i in range(N) if not i in chosen_indices] next_indices.sort() #print next_indices @@ -750,12 +750,12 @@ def selSPEA2(individuals, k): elif len(chosen_indices) > k: # The archive is too large N = len(chosen_indices) - distances = [[0.0] * N for i in xrange(N)] - sorted_indices = [[0] * N for i in xrange(N)] - for i in xrange(N): - for j in xrange(i + 1, N): + distances = [[0.0] * N for i in range(N)] + sorted_indices = [[0] * N for i in range(N)] + for i in range(N): + for j in range(i + 1, N): dist = 0.0 - for l in xrange(L): + for l in range(L): val = individuals[chosen_indices[i]].fitness.values[l] - \ individuals[chosen_indices[j]].fitness.values[l] dist += val * val @@ -764,8 +764,8 @@ def selSPEA2(individuals, k): distances[i][i] = -1 # Insert sort is faster than quick sort for short arrays - for i in xrange(N): - for j in xrange(1, N): + for i in range(N): + for j in range(1, N): l = j while l > 0 and distances[i][j] < distances[i][sorted_indices[i][l - 1]]: sorted_indices[i][l] = sorted_indices[i][l - 1] @@ -777,8 +777,8 @@ def selSPEA2(individuals, k): while size > k: # Search for minimal distance min_pos = 0 - for i in xrange(1, N): - for j in xrange(1, size): + for i in range(1, N): + for j in range(1, size): dist_i_sorted_j = distances[i][sorted_indices[i][j]] dist_min_sorted_j = distances[min_pos][sorted_indices[min_pos][j]] @@ -789,11 +789,11 @@ def selSPEA2(individuals, k): break # Remove minimal distance from sorted_indices - for i in xrange(N): + for i in range(N): distances[i][min_pos] = float("inf") distances[min_pos][i] = float("inf") - for j in xrange(1, size - 1): + for j in range(1, size - 1): if sorted_indices[i][j] == min_pos: sorted_indices[i][j] = sorted_indices[i][j + 1] sorted_indices[i][j + 1] = min_pos diff --git a/deap/tools/indicator.py b/deap/tools/indicator.py index c2376312a..8901466d9 100644 --- a/deap/tools/indicator.py +++ b/deap/tools/indicator.py @@ -25,7 +25,7 @@ def contribution(i): return hv.hypervolume(numpy.concatenate((wobj[:i], wobj[i+1:])), ref) # Parallelization note: Cannot pickle local function - contrib_values = map(contribution, range(len(front))) + contrib_values = list(map(contribution, list(range(len(front))))) # Select the maximum hypervolume value (correspond to the minimum difference) return numpy.argmax(contrib_values) diff --git a/deap/tools/init.py b/deap/tools/init.py index 4d4391769..144bbbb36 100644 --- a/deap/tools/init.py +++ b/deap/tools/init.py @@ -1,4 +1,4 @@ -from __future__ import division + def initRepeat(container, func, n): """Call the function *func* *n* times and return the results in a @@ -22,7 +22,7 @@ def initRepeat(container, func, n): See the :ref:`list-of-floats` and :ref:`population` tutorials for more examples. """ - return container(func() for _ in xrange(n)) + return container(func() for _ in range(n)) def initIterate(container, generator): """Call the function *container* with an iterable as @@ -72,7 +72,7 @@ def initCycle(container, seq_func, n=1): See the :ref:`funky` tutorial for an example. """ - return container(func() for _ in xrange(n) for func in seq_func) + return container(func() for _ in range(n) for func in seq_func) __all__ = ['initRepeat', 'initIterate', 'initCycle'] diff --git a/deap/tools/migration.py b/deap/tools/migration.py index 84f1c0d4c..d9407d5e6 100644 --- a/deap/tools/migration.py +++ b/deap/tools/migration.py @@ -1,4 +1,4 @@ -from __future__ import division + def migRing(populations, k, selection, replacement=None, migarray=None): @@ -31,12 +31,12 @@ def migRing(populations, k, selection, replacement=None, migarray=None): """ nbr_demes = len(populations) if migarray is None: - migarray = range(1, nbr_demes) + [0] + migarray = list(range(1, nbr_demes)) + [0] - immigrants = [[] for i in xrange(nbr_demes)] - emigrants = [[] for i in xrange(nbr_demes)] + immigrants = [[] for i in range(nbr_demes)] + emigrants = [[] for i in range(nbr_demes)] - for from_deme in xrange(nbr_demes): + for from_deme in range(nbr_demes): emigrants[from_deme].extend(selection(populations[from_deme], k)) if replacement is None: # If no replacement strategy is selected, replace those who migrate diff --git a/deap/tools/mutation.py b/deap/tools/mutation.py index 383c58fae..b04d2444b 100644 --- a/deap/tools/mutation.py +++ b/deap/tools/mutation.py @@ -1,4 +1,4 @@ -from __future__ import division + import math import random @@ -41,7 +41,7 @@ def mutGaussian(individual, mu, sigma, indpb): elif len(sigma) < size: raise IndexError("sigma must be at least the size of individual: %d < %d" % (len(sigma), size)) - for i, m, s in zip(xrange(size), mu, sigma): + for i, m, s in zip(range(size), mu, sigma): if random.random() < indpb: individual[i] += random.gauss(m, s) @@ -78,7 +78,7 @@ def mutPolynomialBounded(individual, eta, low, up, indpb): elif len(up) < size: raise IndexError("up must be at least the size of individual: %d < %d" % (len(up), size)) - for i, xl, xu, mp in zip(range(size), low, up, indpb): + for i, xl, xu, mp in zip(list(range(size)), low, up, indpb): if random.random() <= mp: x = individual[i] delta_1 = (x - xl) / (xu - xl) @@ -116,7 +116,7 @@ def mutShuffleIndexes(individual, indpb): functions from the python base :mod:`random` module. """ size = len(individual) - for i in xrange(size): + for i in range(size): if random.random() < indpb: swap_indx = random.randint(0, size - 2) if swap_indx >= i: @@ -141,7 +141,7 @@ def mutFlipBit(individual, indpb): This function uses the :func:`~random.random` function from the python base :mod:`random` module. """ - for i in xrange(len(individual)): + for i in range(len(individual)): if random.random() < indpb: individual[i] = type(individual[i])(not individual[i]) @@ -172,7 +172,7 @@ def mutUniformInt(individual, low, up, indpb): elif len(up) < size: raise IndexError("up must be at least the size of individual: %d < %d" % (len(up), size)) - for i, xl, xu in zip(xrange(size), low, up): + for i, xl, xu in zip(range(size), low, up): if random.random() < indpb: individual[i] = random.randint(xl, xu) @@ -213,7 +213,7 @@ def mutESLogNormal(individual, c, indpb): n = random.gauss(0, 1) t0_n = t0 * n - for indx in xrange(size): + for indx in range(size): if random.random() < indpb: individual.strategy[indx] *= math.exp(t0_n + t * random.gauss(0, 1)) individual[indx] += individual.strategy[indx] * random.gauss(0, 1) diff --git a/deap/tools/selection.py b/deap/tools/selection.py index b3584ecf4..68b03a38d 100644 --- a/deap/tools/selection.py +++ b/deap/tools/selection.py @@ -1,4 +1,4 @@ -from __future__ import division + import random import numpy as np @@ -21,7 +21,7 @@ def selRandom(individuals, k): This function uses the :func:`~random.choice` function from the python base :mod:`random` module. """ - return [random.choice(individuals) for i in xrange(k)] + return [random.choice(individuals) for i in range(k)] def selBest(individuals, k, fit_attr="fitness"): @@ -63,7 +63,7 @@ def selTournament(individuals, k, tournsize, fit_attr="fitness"): :mod:`random` module. """ chosen = [] - for i in xrange(k): + for i in range(k): aspirants = selRandom(individuals, tournsize) chosen.append(max(aspirants, key=attrgetter(fit_attr))) return chosen @@ -90,7 +90,7 @@ def selRoulette(individuals, k, fit_attr="fitness"): s_inds = sorted(individuals, key=attrgetter(fit_attr), reverse=True) sum_fits = sum(getattr(ind, fit_attr).values[0] for ind in individuals) chosen = [] - for i in xrange(k): + for i in range(k): u = random.random() * sum_fits sum_ = 0 for ind in s_inds: @@ -147,7 +147,7 @@ def selDoubleTournament(individuals, k, fitness_size, parsimony_size, fitness_fi def _sizeTournament(individuals, k, select): chosen = [] - for i in xrange(k): + for i in range(k): # Select two individuals from the population # The first individual has to be the shortest prob = parsimony_size / 2. @@ -167,7 +167,7 @@ def _sizeTournament(individuals, k, select): def _fitTournament(individuals, k, select): chosen = [] - for i in xrange(k): + for i in range(k): aspirants = select(individuals, k=fitness_size) chosen.append(max(aspirants, key=attrgetter(fit_attr))) return chosen @@ -198,7 +198,7 @@ def selStochasticUniversalSampling(individuals, k, fit_attr="fitness"): distance = sum_fits / float(k) start = random.uniform(0, distance) - points = [start + i*distance for i in xrange(k)] + points = [start + i*distance for i in range(k)] chosen = [] for p in points: @@ -234,9 +234,9 @@ def selLexicase(individuals, k): if fit_weights[cases[0]] > 0: f = max - best_val_for_case = f(map(lambda x: x.fitness.values[cases[0]], candidates)) + best_val_for_case = f([x.fitness.values[cases[0]] for x in candidates]) - candidates = list(filter(lambda x: x.fitness.values[cases[0]] == best_val_for_case, candidates)) + candidates = list([x for x in candidates if x.fitness.values[cases[0]] == best_val_for_case]) cases.pop(0) selected_individuals.append(random.choice(candidates)) @@ -266,13 +266,13 @@ def selEpsilonLexicase(individuals, k, epsilon): while len(cases) > 0 and len(candidates) > 1: if fit_weights[cases[0]] > 0: - best_val_for_case = max(map(lambda x: x.fitness.values[cases[0]], candidates)) + best_val_for_case = max([x.fitness.values[cases[0]] for x in candidates]) min_val_to_survive_case = best_val_for_case - epsilon - candidates = list(filter(lambda x: x.fitness.values[cases[0]] >= min_val_to_survive_case, candidates)) + candidates = list([x for x in candidates if x.fitness.values[cases[0]] >= min_val_to_survive_case]) else : - best_val_for_case = min(map(lambda x: x.fitness.values[cases[0]], candidates)) + best_val_for_case = min([x.fitness.values[cases[0]] for x in candidates]) max_val_to_survive_case = best_val_for_case + epsilon - candidates = list(filter(lambda x: x.fitness.values[cases[0]] <= max_val_to_survive_case, candidates)) + candidates = list([x for x in candidates if x.fitness.values[cases[0]] <= max_val_to_survive_case]) cases.pop(0) @@ -307,11 +307,11 @@ def selAutomaticEpsilonLexicase(individuals, k): if fit_weights[cases[0]] > 0: best_val_for_case = max(errors_for_this_case) min_val_to_survive = best_val_for_case - median_absolute_deviation - candidates = list(filter(lambda x: x.fitness.values[cases[0]] >= min_val_to_survive, candidates)) + candidates = list([x for x in candidates if x.fitness.values[cases[0]] >= min_val_to_survive]) else : best_val_for_case = min(errors_for_this_case) max_val_to_survive = best_val_for_case + median_absolute_deviation - candidates = list(filter(lambda x: x.fitness.values[cases[0]] <= max_val_to_survive, candidates)) + candidates = list([x for x in candidates if x.fitness.values[cases[0]] <= max_val_to_survive]) cases.pop(0) diff --git a/deap/tools/support.py b/deap/tools/support.py index de0897c0f..c75dd0048 100644 --- a/deap/tools/support.py +++ b/deap/tools/support.py @@ -1,7 +1,7 @@ -from __future__ import division + try: - import cPickle as pickle + import pickle as pickle except ImportError: import pickle @@ -205,7 +205,7 @@ def compile(self, data): values = tuple(self.key(elem) for elem in data) entry = dict() - for key, func in self.functions.iteritems(): + for key, func in self.functions.items(): entry[key] = func(values) return entry @@ -236,7 +236,7 @@ def compile(self, data): :param data: Sequence of objects on which the statistics are computed. """ record = {} - for name, stats in self.items(): + for name, stats in list(self.items()): record[name] = stats.compile(data) return record @@ -255,7 +255,7 @@ def register(self, name, function, *args, **kargs): automatically to the registered function when called, optional. """ - for stats in self.values(): + for stats in list(self.values()): stats.register(name, function, *args, **kargs) class Logbook(list): @@ -339,8 +339,8 @@ def record(self, **infos): in the dictionary are recorded in a chapter entitled as the name of the key part of the pair. Chapters are also Logbook. """ - apply_to_all = {k: v for k, v in infos.items() if not isinstance(v, dict)} - for key, value in infos.items(): + apply_to_all = {k: v for k, v in list(infos.items()) if not isinstance(v, dict)} + for key, value in list(infos.items()): if isinstance(value, dict): chapter_infos = value.copy() chapter_infos.update(apply_to_all) @@ -402,11 +402,11 @@ def __delitem__(self, key): if isinstance(key, slice): for i, in range(*key.indices(len(self))): self.pop(i) - for chapter in self.chapters.values(): + for chapter in list(self.chapters.values()): chapter.pop(i) else: self.pop(key) - for chapter in self.chapters.values(): + for chapter in list(self.chapters.values()): chapter.pop(key) def pop(self, index=0): @@ -431,11 +431,11 @@ def __txt__(self, startindex): if not columns: columns = sorted(self[0].keys()) + sorted(self.chapters.keys()) if not self.columns_len or len(self.columns_len) != len(columns): - self.columns_len = map(len, columns) + self.columns_len = list(map(len, columns)) chapters_txt = {} offsets = defaultdict(int) - for name, chapter in self.chapters.items(): + for name, chapter in list(self.chapters.items()): chapters_txt[name] = chapter.__txt__(startindex) if startindex == 0: offsets[name] = len(chapters_txt[name]) - len(self) @@ -458,17 +458,17 @@ def __txt__(self, startindex): header = [] nlines = 1 if len(self.chapters) > 0: - nlines += max(map(len, chapters_txt.values())) - len(self) + 1 - header = [[] for i in xrange(nlines)] + nlines += max(list(map(len, list(chapters_txt.values())))) - len(self) + 1 + header = [[] for i in range(nlines)] for j, name in enumerate(columns): if name in chapters_txt: length = max(len(line.expandtabs()) for line in chapters_txt[name]) blanks = nlines - 2 - offsets[name] - for i in xrange(blanks): + for i in range(blanks): header[i].append(" " * length) header[blanks].append(name.center(length)) header[blanks+1].append("-" * length) - for i in xrange(offsets[name]): + for i in range(offsets[name]): header[blanks+2+i].append(chapters_txt[name][i]) else: length = max(len(line[j].expandtabs()) for line in str_matrix) diff --git a/doc/code/benchmarks/ackley.py b/doc/code/benchmarks/ackley.py index d5f8c8811..c235aeb67 100644 --- a/doc/code/benchmarks/ackley.py +++ b/doc/code/benchmarks/ackley.py @@ -19,7 +19,7 @@ def ackley_arg0(sol): X = np.arange(-30, 30, 0.5) Y = np.arange(-30, 30, 0.5) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(ackley_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(ackley_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/bohachevsky.py b/doc/code/benchmarks/bohachevsky.py index 7feddad75..eb27f9776 100644 --- a/doc/code/benchmarks/bohachevsky.py +++ b/doc/code/benchmarks/bohachevsky.py @@ -19,7 +19,7 @@ def bohachevsky_arg0(sol): X = np.arange(-15, 15, 0.5) Y = np.arange(-15, 15, 0.5) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(bohachevsky_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(bohachevsky_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/griewank.py b/doc/code/benchmarks/griewank.py index dfba47727..cf4d4a016 100644 --- a/doc/code/benchmarks/griewank.py +++ b/doc/code/benchmarks/griewank.py @@ -18,7 +18,7 @@ def griewank_arg0(sol): X = np.arange(-50, 50, 0.5) Y = np.arange(-50, 50, 0.5) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(griewank_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(griewank_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/h1.py b/doc/code/benchmarks/h1.py index d23ec16be..12f0695d9 100644 --- a/doc/code/benchmarks/h1.py +++ b/doc/code/benchmarks/h1.py @@ -19,7 +19,7 @@ def h1_arg0(sol): X = np.arange(-25, 25, 0.5) Y = np.arange(-25, 25, 0.5) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(h1_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(h1_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/himmelblau.py b/doc/code/benchmarks/himmelblau.py index 9b61b82e8..632443cd8 100644 --- a/doc/code/benchmarks/himmelblau.py +++ b/doc/code/benchmarks/himmelblau.py @@ -18,7 +18,7 @@ def himmelblau_arg0(sol): X = np.arange(-6, 6, 0.1) Y = np.arange(-6, 6, 0.1) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(himmelblau_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(himmelblau_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/movingsc1.py b/doc/code/benchmarks/movingsc1.py index c0c1cf7d1..d4779d78f 100644 --- a/doc/code/benchmarks/movingsc1.py +++ b/doc/code/benchmarks/movingsc1.py @@ -24,7 +24,7 @@ X = np.arange(0, 100, 1.0) Y = np.arange(0, 100, 1.0) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(lambda x: mp(x)[0], zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter([mp(x)[0] for x in zip(X.flat,Y.flat)], dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/rastrigin.py b/doc/code/benchmarks/rastrigin.py index 7ed2f91b3..a6a6fa920 100644 --- a/doc/code/benchmarks/rastrigin.py +++ b/doc/code/benchmarks/rastrigin.py @@ -17,7 +17,7 @@ def rastrigin_arg0(sol): X = np.arange(-5, 5, 0.1) Y = np.arange(-5, 5, 0.1) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(rastrigin_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(rastrigin_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/rosenbrock.py b/doc/code/benchmarks/rosenbrock.py index 6b307af4e..d77b655e2 100644 --- a/doc/code/benchmarks/rosenbrock.py +++ b/doc/code/benchmarks/rosenbrock.py @@ -19,7 +19,7 @@ def rosenbrock_arg0(sol): X = np.arange(-2, 2, 0.1) Y = np.arange(-1, 3, 0.1) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(rosenbrock_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(rosenbrock_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/schaffer.py b/doc/code/benchmarks/schaffer.py index ed03acd6b..5a0d98900 100644 --- a/doc/code/benchmarks/schaffer.py +++ b/doc/code/benchmarks/schaffer.py @@ -18,7 +18,7 @@ def schaffer_arg0(sol): X = np.arange(-25, 25, 0.25) Y = np.arange(-25, 25, 0.25) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(schaffer_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(schaffer_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/schwefel.py b/doc/code/benchmarks/schwefel.py index 4465f5f87..28394e2e5 100644 --- a/doc/code/benchmarks/schwefel.py +++ b/doc/code/benchmarks/schwefel.py @@ -18,7 +18,7 @@ def schwefel_arg0(sol): X = np.arange(-500, 500, 10) Y = np.arange(-500, 500, 10) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(schwefel_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(schwefel_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/benchmarks/shekel.py b/doc/code/benchmarks/shekel.py index c762017dd..b1fe67507 100644 --- a/doc/code/benchmarks/shekel.py +++ b/doc/code/benchmarks/shekel.py @@ -26,7 +26,7 @@ def shekel_arg0(sol): X = np.arange(0, 1, 0.01) Y = np.arange(0, 1, 0.01) X, Y = np.meshgrid(X, Y) -Z = np.fromiter(map(shekel_arg0, zip(X.flat,Y.flat)), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) +Z = np.fromiter(list(map(shekel_arg0, list(zip(X.flat,Y.flat)))), dtype=np.float, count=X.shape[0]*X.shape[1]).reshape(X.shape) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) diff --git a/doc/code/tutorials/part_1/1_where_to_start.py b/doc/code/tutorials/part_1/1_where_to_start.py index 7b51cdafb..64507271e 100644 --- a/doc/code/tutorials/part_1/1_where_to_start.py +++ b/doc/code/tutorials/part_1/1_where_to_start.py @@ -30,7 +30,7 @@ def main(): CXPB, MUTPB, NGEN = 0.5, 0.2, 40 # Evaluate the entire population - fitnesses = map(toolbox.evaluate, pop) + fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit @@ -38,7 +38,7 @@ def main(): # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals - offspring = map(toolbox.clone, offspring) + offspring = list(map(toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): @@ -54,7 +54,7 @@ def main(): # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] - fitnesses = map(toolbox.evaluate, invalid_ind) + fitnesses = list(map(toolbox.evaluate, invalid_ind)) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit diff --git a/doc/code/tutorials/part_2/2_2_2_permutation.py b/doc/code/tutorials/part_2/2_2_2_permutation.py index 9a3c23e51..8ad319d7a 100644 --- a/doc/code/tutorials/part_2/2_2_2_permutation.py +++ b/doc/code/tutorials/part_2/2_2_2_permutation.py @@ -11,6 +11,6 @@ IND_SIZE=10 toolbox = base.Toolbox() -toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) +toolbox.register("indices", random.sample, list(range(IND_SIZE)), IND_SIZE) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices) diff --git a/doc/code/tutorials/part_2/2_2_5_particle.py b/doc/code/tutorials/part_2/2_2_5_particle.py index 4f53738c0..e2a331dda 100644 --- a/doc/code/tutorials/part_2/2_2_5_particle.py +++ b/doc/code/tutorials/part_2/2_2_5_particle.py @@ -10,8 +10,8 @@ smin=None, smax=None, best=None) def initParticle(pcls, size, pmin, pmax, smin, smax): - part = pcls(random.uniform(pmin, pmax) for _ in xrange(size)) - part.speed = [random.uniform(smin, smax) for _ in xrange(size)] + part = pcls(random.uniform(pmin, pmax) for _ in range(size)) + part.speed = [random.uniform(smin, smax) for _ in range(size)] part.smin = smin part.smax = smax return part diff --git a/doc/code/tutorials/part_2/2_3_3_swarm.py b/doc/code/tutorials/part_2/2_3_3_swarm.py index f59c8a9d0..aa87ba735 100644 --- a/doc/code/tutorials/part_2/2_3_3_swarm.py +++ b/doc/code/tutorials/part_2/2_3_3_swarm.py @@ -11,8 +11,8 @@ creator.create("Swarm", list, gbest=None, gbestfit=creator.FitnessMax) def initParticle(pcls, size, pmin, pmax, smin, smax): - part = pcls(random.uniform(pmin, pmax) for _ in xrange(size)) - part.speed = [random.uniform(smin, smax) for _ in xrange(size)] + part = pcls(random.uniform(pmin, pmax) for _ in range(size)) + part.speed = [random.uniform(smin, smax) for _ in range(size)] part.smin = smin part.smax = smax return part diff --git a/doc/code/tutorials/part_2/2_3_4_demes.py b/doc/code/tutorials/part_2/2_3_4_demes.py index a0989c2d8..f7b56fd3c 100644 --- a/doc/code/tutorials/part_2/2_3_4_demes.py +++ b/doc/code/tutorials/part_2/2_3_4_demes.py @@ -11,7 +11,7 @@ IND_SIZE=10 toolbox = base.Toolbox() -toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) +toolbox.register("indices", random.sample, list(range(IND_SIZE)), IND_SIZE) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices) toolbox.register("deme", tools.initRepeat, list, toolbox.individual) diff --git a/doc/code/tutorials/part_3/3_6_2_tool_decoration.py b/doc/code/tutorials/part_3/3_6_2_tool_decoration.py index 58c972c76..c006f510b 100644 --- a/doc/code/tutorials/part_3/3_6_2_tool_decoration.py +++ b/doc/code/tutorials/part_3/3_6_2_tool_decoration.py @@ -10,7 +10,7 @@ def decorator(func): def wrapper(*args, **kargs): offspring = func(*args, **kargs) for child in offspring: - for i in xrange(len(child)): + for i in range(len(child)): if child[i] > max: child[i] = max elif child[i] < min: diff --git a/doc/code/tutorials/part_3/3_6_using_the_toolbox.py b/doc/code/tutorials/part_3/3_6_using_the_toolbox.py index 8f2164db9..fd4453cb9 100644 --- a/doc/code/tutorials/part_3/3_6_using_the_toolbox.py +++ b/doc/code/tutorials/part_3/3_6_using_the_toolbox.py @@ -31,7 +31,7 @@ def evaluateInd(individual): # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals - offspring = map(toolbox.clone, offspring) + offspring = list(map(toolbox.clone, offspring)) # Apply crossover on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): diff --git a/doc/code/tutorials/part_3/3_7_variations.py b/doc/code/tutorials/part_3/3_7_variations.py index dcc9814f0..79f6218ae 100644 --- a/doc/code/tutorials/part_3/3_7_variations.py +++ b/doc/code/tutorials/part_3/3_7_variations.py @@ -34,7 +34,7 @@ def onemax(individual): for g in range(NGEN): # Select and clone the next generation individuals - offspring = map(toolbox.clone, toolbox.select(pop, len(pop))) + offspring = list(map(toolbox.clone, toolbox.select(pop, len(pop)))) # Apply crossover and mutation on the offspring offspring = algorithms.varAnd(offspring, toolbox, CXPB, MUTPB) diff --git a/doc/code/tutorials/part_3/3_next_step.py b/doc/code/tutorials/part_3/3_next_step.py index ff59e088a..7ac7e83ac 100644 --- a/doc/code/tutorials/part_3/3_next_step.py +++ b/doc/code/tutorials/part_3/3_next_step.py @@ -17,8 +17,8 @@ ind1 = toolbox.individual() -print ind1 # [0.86..., 0.27..., 0.70..., 0.03..., 0.87...] -print ind1.fitness.valid # False +print(ind1) # [0.86..., 0.27..., 0.70..., 0.03..., 0.87...] +print(ind1.fitness.valid) # False ## 3.2 Evaluation def evaluate(individual): @@ -28,16 +28,16 @@ def evaluate(individual): return a, 1. / b ind1.fitness.values = evaluate(ind1) -print ind1.fitness.valid # True -print ind1.fitness # (2.73, 0.2) +print(ind1.fitness.valid) # True +print(ind1.fitness) # (2.73, 0.2) ## 3.3 Mutation mutant = toolbox.clone(ind1) ind2, = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2) del mutant.fitness.values -print ind2 is mutant # True -print mutant is ind1 # False +print(ind2 is mutant) # True +print(mutant is ind1) # False ## 3.4 Crossover child1, child2 = [toolbox.clone(ind) for ind in (ind1, ind2)] @@ -47,7 +47,7 @@ def evaluate(individual): ## 3.5 Selection selected = tools.selBest([child1, child2], 2) -print child1 in selected # True +print(child1 in selected) # True ## 3.5 Note LAMBDA = 10 diff --git a/doc/code/tutorials/part_3/logbook.py b/doc/code/tutorials/part_3/logbook.py index 6182d47ab..7a40589f6 100644 --- a/doc/code/tutorials/part_3/logbook.py +++ b/doc/code/tutorials/part_3/logbook.py @@ -21,9 +21,9 @@ logbook.header = "gen", "avg", "spam" print(logbook) -print(logbook.stream) +print((logbook.stream)) logbook.record(gen=1, evals=15, **record) -print(logbook.stream) +print((logbook.stream)) from multistats import record diff --git a/doc/code/tutorials/part_3/multistats.py b/doc/code/tutorials/part_3/multistats.py index e83740b11..88a44f72d 100644 --- a/doc/code/tutorials/part_3/multistats.py +++ b/doc/code/tutorials/part_3/multistats.py @@ -47,7 +47,7 @@ def evalSymbReg(individual, points): pop = toolbox.population(n=100) # Evaluate the individuals -fitnesses = map(toolbox.evaluate, pop) +fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit diff --git a/doc/code/tutorials/part_3/stats.py b/doc/code/tutorials/part_3/stats.py index 001407ac1..f60122435 100644 --- a/doc/code/tutorials/part_3/stats.py +++ b/doc/code/tutorials/part_3/stats.py @@ -31,7 +31,7 @@ def evalOneMax(individual): pop = toolbox.population(n=100) # Evaluate the individuals -fitnesses = map(toolbox.evaluate, pop) +fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit diff --git a/doc/code/tutorials/part_4/4_4_Using_Cpp_NSGA.py b/doc/code/tutorials/part_4/4_4_Using_Cpp_NSGA.py index c23bba4d0..bf73da43f 100644 --- a/doc/code/tutorials/part_4/4_4_Using_Cpp_NSGA.py +++ b/doc/code/tutorials/part_4/4_4_Using_Cpp_NSGA.py @@ -34,7 +34,7 @@ def genWire(dimension): def genNetwork(dimension, min_size, max_size): size = random.randint(min_size, max_size) - return [genWire(dimension) for i in xrange(size)] + return [genWire(dimension) for i in range(size)] def mutWire(individual, dimension, indpb): for index, elem in enumerate(individual): @@ -91,8 +91,8 @@ def main(): stats.update(population) # Begin the evolution - for g in xrange(NGEN): - print "-- Generation %i --" % g + for g in range(NGEN): + print("-- Generation %i --" % g) offspring = [toolbox.clone(ind) for ind in population] # Apply crossover and mutation @@ -121,21 +121,21 @@ def main(): for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit - print " Evaluated %i individuals" % len(invalid_ind) + print(" Evaluated %i individuals" % len(invalid_ind)) population = toolbox.select(population+offspring, len(offspring)) hof.update(population) stats.update(population) - print " Min %s" % stats.Min[0][-1][0] - print " Max %s" % stats.Max[0][-1][0] - print " Avg %s" % stats.Avg[0][-1][0] - print " Std %s" % stats.Std[0][-1][0] + print(" Min %s" % stats.Min[0][-1][0]) + print(" Max %s" % stats.Max[0][-1][0]) + print(" Avg %s" % stats.Avg[0][-1][0]) + print(" Std %s" % stats.Std[0][-1][0]) best_network = sn.SortingNetwork(INPUTS, hof[0]) - print best_network - print best_network.draw() - print "%i errors, length %i, depth %i" % hof[0].fitness.values + print(best_network) + print(best_network.draw()) + print("%i errors, length %i, depth %i" % hof[0].fitness.values) return population, stats, hof diff --git a/doc/code/tutorials/part_4/4_5_home_made_eval_func.py b/doc/code/tutorials/part_4/4_5_home_made_eval_func.py index 8aa405dd9..7c7d29db1 100644 --- a/doc/code/tutorials/part_4/4_5_home_made_eval_func.py +++ b/doc/code/tutorials/part_4/4_5_home_made_eval_func.py @@ -40,7 +40,7 @@ def genWire(dimension): def genNetwork(dimension, min_size, max_size): size = random.randint(min_size, max_size) - return [genWire(dimension) for i in xrange(size)] + return [genWire(dimension) for i in range(size)] def mutWire(individual, dimension, indpb): for index, elem in enumerate(individual): @@ -97,9 +97,9 @@ def main(): stats.update(population) # Begin the evolution - for g in xrange(NGEN): + for g in range(NGEN): t1 = time.time() - print "-- Generation %i --" % g + print("-- Generation %i --" % g) offspring = [toolbox.clone(ind) for ind in population] t2 = time.time() # Apply crossover and mutation @@ -128,29 +128,29 @@ def main(): for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit - print " Evaluated %i individuals" % len(invalid_ind) + print(" Evaluated %i individuals" % len(invalid_ind)) t5 = time.time() population = toolbox.select(population+offspring, len(offspring)) t6 = time.time() #hof.update(population) stats.update(population) t7 = time.time() - print stats + print(stats) print("Times :") - print("Clone : " + str(t2-t1) + " (" + str((t2-t1)/(t7-t1)) +"%)") - print("Cx : " + str(t3-t2) + " (" + str((t3-t2)/(t7-t1)) +"%)") - print("Mut : " + str(t4-t3) + " (" + str((t4-t3)/(t7-t1)) +"%)") - print("Eval : " + str(t5-t4) + " (" + str((t5-t4)/(t7-t1)) +"%)") - print("Select : " + str(t6-t5) + " (" + str((t6-t5)/(t7-t1)) +"%)") - print("HOF + stats : " + str(t7-t6) + " (" + str((t7-t6)/(t7-t1)) +"%)") - print("TOTAL : " + str(t7-t1)) + print(("Clone : " + str(t2-t1) + " (" + str((t2-t1)/(t7-t1)) +"%)")) + print(("Cx : " + str(t3-t2) + " (" + str((t3-t2)/(t7-t1)) +"%)")) + print(("Mut : " + str(t4-t3) + " (" + str((t4-t3)/(t7-t1)) +"%)")) + print(("Eval : " + str(t5-t4) + " (" + str((t5-t4)/(t7-t1)) +"%)")) + print(("Select : " + str(t6-t5) + " (" + str((t6-t5)/(t7-t1)) +"%)")) + print(("HOF + stats : " + str(t7-t6) + " (" + str((t7-t6)/(t7-t1)) +"%)")) + print(("TOTAL : " + str(t7-t1))) best_network = sn.SortingNetwork(INPUTS, hof[0]) - print best_network - print best_network.draw() - print "%i errors, length %i, depth %i" % hof[0].fitness.values + print(best_network) + print(best_network.draw()) + print("%i errors, length %i, depth %i" % hof[0].fitness.values) return population, stats, hof diff --git a/doc/code/tutorials/part_4/sortingnetwork.py b/doc/code/tutorials/part_4/sortingnetwork.py index 636e412a6..ca5958213 100644 --- a/doc/code/tutorials/part_4/sortingnetwork.py +++ b/doc/code/tutorials/part_4/sortingnetwork.py @@ -19,7 +19,7 @@ def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 - pools = map(tuple, args) * kwds.get('repeat', 1) + pools = list(map(tuple, args)) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] @@ -55,7 +55,7 @@ def addConnector(self, wire1, wire2): self.append({wire1: wire2}) return - for wires in last_level.iteritems(): + for wires in last_level.items(): if wires[1] >= wire1 and wires[0] <= wire2: self.append({wire1: wire2}) return @@ -65,7 +65,7 @@ def addConnector(self, wire1, wire2): def sort(self, values): """Sort the values in-place based on the connectors in the network.""" for level in self: - for wire1, wire2 in level.iteritems(): + for wire1, wire2 in level.items(): if values[wire1] > values[wire2]: values[wire1], values[wire2] = values[wire2], values[wire1] @@ -75,7 +75,7 @@ def assess(self, cases=None): the network dimensionality. """ if cases is None: - cases = product(range(2), repeat=self.dimension) + cases = product(list(range(2)), repeat=self.dimension) misses = 0 ordered = [[0]*(self.dimension-i) + [1]*i for i in range(self.dimension+1)] @@ -92,19 +92,19 @@ def draw(self): str_wires[0][1] = " o" str_spaces = [] - for i in xrange(1, self.dimension): + for i in range(1, self.dimension): str_wires.append(["-"]*7 * self.depth) str_spaces.append([" "]*7 * self.depth) str_wires[i][0] = str(i) str_wires[i][1] = " o" for index, level in enumerate(self): - for wire1, wire2 in level.iteritems(): + for wire1, wire2 in level.items(): str_wires[wire1][(index+1)*6] = "x" str_wires[wire2][(index+1)*6] = "x" - for i in xrange(wire1, wire2): + for i in range(wire1, wire2): str_spaces[i][(index+1)*6+1] = "|" - for i in xrange(wire1+1, wire2): + for i in range(wire1+1, wire2): str_wires[i][(index+1)*6] = "|" network_draw = "".join(str_wires[0]) diff --git a/doc/conf.py b/doc/conf.py index 37827cbf1..6a1c2b2fd 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -51,8 +51,8 @@ master_doc = 'index' # General information about the project. -project = u'DEAP' -copyright = u'2009-%s, DEAP Project' % time.strftime('%Y') +project = 'DEAP' +copyright = '2009-%s, DEAP Project' % time.strftime('%Y') # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -224,8 +224,8 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('contents', 'DEAP.tex', u'DEAP Documentation', - u'DEAP Project', 'manual'), + ('contents', 'DEAP.tex', 'DEAP Documentation', + 'DEAP Project', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of diff --git a/examples/bbob.py b/examples/bbob.py index 91ef6f5fe..0b2725878 100644 --- a/examples/bbob.py +++ b/examples/bbob.py @@ -108,7 +108,7 @@ def main(func, dim, maxfuncevals, ftarget=None): # Iterate over all the instance of a single problem # Rotation, translation, etc. - for instance in chain(range(1, 6), range(21, 31)): + for instance in chain(list(range(1, 6)), list(range(21, 31))): # Set the function to be used (problem) in the logger e.setfun(*bn.instantiate(f_name, iinstance=instance)) @@ -129,9 +129,9 @@ def main(func, dim, maxfuncevals, ftarget=None): e.finalizerun() - print('f%d in %d-D, instance %d: FEs=%d with %d restarts, ' + print(('f%d in %d-D, instance %d: FEs=%d with %d restarts, ' 'fbest-ftarget=%.4e' % (f_name, dim, instance, e.evaluations, restarts, - e.fbest - e.ftarget)) + e.fbest - e.ftarget))) - print('date and time: %s' % time.asctime()) + print(('date and time: %s' % time.asctime())) diff --git a/examples/coev/coop_adapt.py b/examples/coev/coop_adapt.py index 13e627ed0..54fd22608 100644 --- a/examples/coev/coop_adapt.py +++ b/examples/coev/coop_adapt.py @@ -89,7 +89,7 @@ def main(extended=True, verbose=True): logbook.record(gen=g, species=i, evals=len(s), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Select the individuals species[i] = toolbox.select(s, len(s)) # Tournament selection @@ -118,7 +118,7 @@ def main(extended=True, verbose=True): if extended: for r in representatives: # print individuals without noise - print("".join(str(x) for x, y in zip(r, noise) if y == "*")) + print(("".join(str(x) for x, y in zip(r, noise) if y == "*"))) if plt and extended: # Do the final plotting diff --git a/examples/coev/coop_evol.py b/examples/coev/coop_evol.py index c42d4d216..c0893c84b 100644 --- a/examples/coev/coop_evol.py +++ b/examples/coev/coop_evol.py @@ -99,7 +99,7 @@ def main(extended=True, verbose=True): logbook.record(gen=g, species=j, evals=len(s), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Select the individuals species[i] = toolbox.select(s, len(s)) # Tournament selection @@ -133,7 +133,7 @@ def main(extended=True, verbose=True): for i in range(len(species)): contributions.append(toolbox.evaluateContribution(representatives, target_set, i)[0]) - for i in reversed(range(len(species))): + for i in reversed(list(range(len(species)))): if contributions[i] < EXTINCTION_TRESHOLD: species.pop(i) species_index.pop(i) @@ -151,14 +151,14 @@ def main(extended=True, verbose=True): if extended: for r in representatives: # print final representatives without noise - print("".join(str(x) for x, y in zip(r, noise) if y == "*")) + print(("".join(str(x) for x, y in zip(r, noise) if y == "*"))) if extended and plt: # Plotting of the evolution line1, = plt.plot(collab, "--", color="k") for con in contribs: try: - con, g = zip(*con) + con, g = list(zip(*con)) line2, = plt.plot(g, con, "-", color="k") except ValueError: pass diff --git a/examples/coev/coop_gen.py b/examples/coev/coop_gen.py index 251151eb1..179cc9220 100644 --- a/examples/coev/coop_gen.py +++ b/examples/coev/coop_gen.py @@ -91,7 +91,7 @@ def main(extended=True, verbose=True): logbook.record(gen=g, species=i, evals=len(s), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Select the individuals species[i] = toolbox.select(s, len(s)) # Tournament selection @@ -113,7 +113,7 @@ def main(extended=True, verbose=True): if extended: for r in representatives: # print individuals without noise - print("".join(str(x) for x, y in zip(r, noise) if y == "*")) + print(("".join(str(x) for x, y in zip(r, noise) if y == "*"))) if plt and extended: # Do the final plotting diff --git a/examples/coev/coop_niche.py b/examples/coev/coop_niche.py index 1fab7bbac..8f2e1541c 100644 --- a/examples/coev/coop_niche.py +++ b/examples/coev/coop_niche.py @@ -84,7 +84,7 @@ def main(extended=True, verbose=True): logbook.record(gen=g, species=i, evals=len(s), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Select the individuals species[i] = toolbox.select(s, len(s)) # Tournament selection @@ -95,7 +95,7 @@ def main(extended=True, verbose=True): if extended: for r in representatives: - print("".join(str(x) for x in r)) + print(("".join(str(x) for x in r))) if __name__ == "__main__": main() diff --git a/examples/coev/hillis.py b/examples/coev/hillis.py index 14b9bdc61..e6a7b4e5f 100644 --- a/examples/coev/hillis.py +++ b/examples/coev/hillis.py @@ -134,7 +134,7 @@ def main(): hof.update(hosts) record = hstats.compile(hosts) logbook.record(gen=0, evals=len(hosts), **record) - print(logbook.stream) + print((logbook.stream)) for g in range(1, MAXGEN): @@ -151,12 +151,12 @@ def main(): hof.update(hosts) record = hstats.compile(hosts) logbook.record(gen=g, evals=len(hosts), **record) - print(logbook.stream) + print((logbook.stream)) best_network = sn.SortingNetwork(INPUTS, hof[0]) print(best_network) - print(best_network.draw()) - print("%i errors" % best_network.assess()) + print((best_network.draw())) + print(("%i errors" % best_network.assess())) return hosts, logbook, hof diff --git a/examples/coev/symbreg.py b/examples/coev/symbreg.py index 91240a301..b462899a0 100644 --- a/examples/coev/symbreg.py +++ b/examples/coev/symbreg.py @@ -69,7 +69,7 @@ def main(): record = stats.compile(pop_gp) logbook.record(gen=0, type='gp', evals=len(pop_gp), **record) - print(logbook.stream) + print((logbook.stream)) CXPB, MUTPB, NGEN = 0.5, 0.2, 50 @@ -121,15 +121,15 @@ def main(): record = stats.compile(pop_gp) logbook.record(gen=g, type='gp', evals=len(pop_gp), **record) - print(logbook.stream) + print((logbook.stream)) best_ga = tools.selBest(pop_ga, 1)[0] best_gp = tools.selBest(pop_gp, 1)[0] - print("Best individual GA is %s, %s" % (best_ga, best_ga.fitness.values)) - print("Best individual GP is %s, %s" % (best_gp, best_gp.fitness.values)) + print(("Best individual GA is %s, %s" % (best_ga, best_ga.fitness.values))) + print(("Best individual GP is %s, %s" % (best_gp, best_gp.fitness.values))) return pop_ga, pop_gp, best_ga, best_gp, logbook diff --git a/examples/de/basic.py b/examples/de/basic.py index 64aaeca0e..588b381eb 100644 --- a/examples/de/basic.py +++ b/examples/de/basic.py @@ -61,7 +61,7 @@ def main(): record = stats.compile(pop) logbook.record(gen=0, evals=len(pop), **record) - print(logbook.stream) + print((logbook.stream)) for g in range(1, NGEN): for k, agent in enumerate(pop): @@ -77,9 +77,9 @@ def main(): hof.update(pop) record = stats.compile(pop) logbook.record(gen=g, evals=len(pop), **record) - print(logbook.stream) + print((logbook.stream)) - print("Best individual is ", hof[0], hof[0].fitness.values[0]) + print(("Best individual is ", hof[0], hof[0].fitness.values[0])) if __name__ == "__main__": main() diff --git a/examples/de/dynamic.py b/examples/de/dynamic.py index c58a971a9..d82f1723b 100644 --- a/examples/de/dynamic.py +++ b/examples/de/dynamic.py @@ -81,7 +81,7 @@ def main(verbose=True): logbook.record(gen=0, evals=mpb.nevals, error=mpb.currentError(), offline_error=mpb.offlineError(), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) g = 1 while mpb.nevals < 5e5: @@ -93,7 +93,7 @@ def main(verbose=True): # Apply exclusion rexcl = (BOUNDS[1] - BOUNDS[0]) / (2 * NPOP**(1.0/NDIM)) - for i, j in itertools.combinations(range(NPOP), 2): + for i, j in itertools.combinations(list(range(NPOP)), 2): if bests[i].fitness.valid and bests[j].fitness.valid: d = sum((bests[i][k] - bests[j][k])**2 for k in range(NDIM)) d = math.sqrt(d) @@ -116,7 +116,7 @@ def main(verbose=True): logbook.record(gen=g, evals=mpb.nevals, error=mpb.currentError(), offline_error=mpb.offlineError(), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Evolve the sub-populations for idx, subpop in enumerate(populations): diff --git a/examples/de/sphere.py b/examples/de/sphere.py index aa9a263c5..8c9adb1cb 100644 --- a/examples/de/sphere.py +++ b/examples/de/sphere.py @@ -50,7 +50,7 @@ def cxExponential(x, y, cr): size = len(x) index = random.randrange(size) # Loop on the indices index -> end, then on 0 -> index - for i in chain(range(index, size), range(0, index)): + for i in chain(list(range(index, size)), list(range(0, index))): x[i] = y[i] if random.random() < cr: break @@ -88,7 +88,7 @@ def main(): record = stats.compile(pop) logbook.record(gen=0, evals=len(pop), **record) - print(logbook.stream) + print((logbook.stream)) for g in range(1, NGEN): children = [] @@ -111,10 +111,10 @@ def main(): hof.update(pop) record = stats.compile(pop) logbook.record(gen=g, evals=len(pop), **record) - print(logbook.stream) + print((logbook.stream)) - print("Best individual is ", hof[0]) - print("with fitness", hof[0].fitness.values[0]) + print(("Best individual is ", hof[0])) + print(("with fitness", hof[0].fitness.values[0])) return logbook if __name__ == "__main__": diff --git a/examples/es/cma_bipop.py b/examples/es/cma_bipop.py index 236c8cd4d..fb84bf89a 100644 --- a/examples/es/cma_bipop.py +++ b/examples/es/cma_bipop.py @@ -124,7 +124,7 @@ def main(verbose=True): record = stats.compile(population) logbooks[-1].record(gen=t, evals=lambda_, restart=i, regime=regime, **record) if verbose: - print(logbooks[-1].stream) + print((logbooks[-1].stream)) # Update the strategy with the evaluated individuals toolbox.update(population) @@ -189,8 +189,8 @@ def main(verbose=True): # The main axis std has no effect conditions["NoEffectCoor"] = True - stop_causes = [k for k, v in conditions.items() if v] - print("Stopped because of condition%s %s" % ((":" if len(stop_causes) == 1 else "s:"), ",".join(stop_causes))) + stop_causes = [k for k, v in list(conditions.items()) if v] + print(("Stopped because of condition%s %s" % ((":" if len(stop_causes) == 1 else "s:"), ",".join(stop_causes)))) i += 1 return halloffame diff --git a/examples/es/cma_mo.py b/examples/es/cma_mo.py index c50adce0b..a4319f555 100644 --- a/examples/es/cma_mo.py +++ b/examples/es/cma_mo.py @@ -109,10 +109,10 @@ def main(): record = stats.compile(population) if stats is not None else {} logbook.record(gen=gen, nevals=len(population), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) if verbose: - print("Final population hypervolume is %f" % hypervolume(strategy.parents, [11.0, 11.0])) + print(("Final population hypervolume is %f" % hypervolume(strategy.parents, [11.0, 11.0]))) # Note that we use a penalty to guide the search to feasible solutions, # but there is no guarantee that individuals are valid. @@ -122,10 +122,10 @@ def main(): dist = distance(closest_feasible(ind), ind) if numpy.isclose(dist, 0.0, rtol=1.e-5, atol=1.e-5): num_valid += 1 - print("Number of valid individuals is %d/%d" % (num_valid, len(strategy.parents))) + print(("Number of valid individuals is %d/%d" % (num_valid, len(strategy.parents)))) print("Final population:") - print(numpy.asarray(strategy.parents)) + print((numpy.asarray(strategy.parents))) if create_plot: interactive = 0 diff --git a/examples/es/cma_plotting.py b/examples/es/cma_plotting.py index 2f41b0886..fb60b8ce0 100644 --- a/examples/es/cma_plotting.py +++ b/examples/es/cma_plotting.py @@ -81,7 +81,7 @@ def main(verbose=True): logbook.record(evals=len(population), gen=gen, **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Save more data along the evolution for latter plotting # diagD is sorted and sqrooted in the update method diff --git a/examples/es/onefifth.py b/examples/es/onefifth.py index 4e86ed17f..e619b03e6 100644 --- a/examples/es/onefifth.py +++ b/examples/es/onefifth.py @@ -72,7 +72,7 @@ def main(): sigma = sigma * alpha**(-0.25) logbook.record(gen=g, fitness=best.fitness.values) - print(logbook.stream) + print((logbook.stream)) return best diff --git a/examples/ga/evosn.py b/examples/ga/evosn.py index a28daa6e2..30925e630 100644 --- a/examples/ga/evosn.py +++ b/examples/ga/evosn.py @@ -94,7 +94,7 @@ def main(): hof.update(population) record = stats.compile(population) logbook.record(gen=0, evals=len(population), **record) - print(logbook.stream) + print((logbook.stream)) # Begin the evolution for g in range(1, NGEN): @@ -130,13 +130,13 @@ def main(): hof.update(population) record = stats.compile(population) logbook.record(gen=g, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) best_network = sn.SortingNetwork(INPUTS, hof[0]) print(stats) print(best_network) - print(best_network.draw()) - print("%i errors, length %i, depth %i" % hof[0].fitness.values) + print((best_network.draw())) + print(("%i errors, length %i, depth %i" % hof[0].fitness.values)) return population, logbook, hof diff --git a/examples/ga/knn.py b/examples/ga/knn.py index 107797b83..420468a05 100644 --- a/examples/ga/knn.py +++ b/examples/ga/knn.py @@ -56,14 +56,14 @@ def predict(self, data, features=None): classes = dict((cls, 0) for cls in self.classes) for n in nns[:self.k]: classes[self.labels[n]] += 1 - labels = sorted(classes.items(), key=operator.itemgetter(1))[-1][0] + labels = sorted(list(classes.items()), key=operator.itemgetter(1))[-1][0] elif data.ndim == 2: labels = list() for i, d in enumerate(data): classes = dict((cls, 0) for cls in self.classes) for n in nns[i, :self.k]: classes[self.labels[n]] += 1 - labels.append(sorted(classes.items(), key=operator.itemgetter(1))[-1][0]) + labels.append(sorted(list(classes.items()), key=operator.itemgetter(1))[-1][0]) return labels @@ -98,6 +98,6 @@ def classification_rate(features): knn = KNN(1) knn.train(trainset, trainlabels) print("Single Data ===========") - print(knn.predict([1, 0], [1, 1])) + print((knn.predict([1, 0], [1, 1]))) print("Multiple Data ===========") - print(knn.predict([[1, 3], [1, 0]], [1, 1])) + print((knn.predict([[1, 3], [1, 0]], [1, 1]))) diff --git a/examples/ga/mo_rhv.py b/examples/ga/mo_rhv.py index 3c3bacd82..0b2a8a336 100644 --- a/examples/ga/mo_rhv.py +++ b/examples/ga/mo_rhv.py @@ -77,7 +77,7 @@ def contribution(i): return total_hv - hv.hypervolume(numpy.concatenate((wobj[:i], wobj[i+1:])), ref) # Parallelization note: Cannot pickle local function - return map(contribution, range(len(front))) + return list(map(contribution, list(range(len(front))))) toolbox.register("attr_float", uniform, BOUND_LOW, BOUND_UP, NDIM) @@ -117,7 +117,7 @@ def main(seed=None): record = stats.compile(pop) logbook.record(gen=0, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) # Begin the generational process for gen in range(1, NGEN): @@ -162,9 +162,9 @@ def main(seed=None): record = stats.compile(pop) logbook.record(gen=gen, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) - print("Final population hypervolume is %f" % hypervolume(pop, [11.0, 11.0])) + print(("Final population hypervolume is %f" % hypervolume(pop, [11.0, 11.0]))) return pop, logbook diff --git a/examples/ga/nqueens.py b/examples/ga/nqueens.py index 44837e4c5..9fda92d1f 100644 --- a/examples/ga/nqueens.py +++ b/examples/ga/nqueens.py @@ -62,7 +62,7 @@ def evalNQueens(individual): #Since there is only one queen per line, #individual are represented by a permutation toolbox = base.Toolbox() -toolbox.register("permutation", random.sample, range(NB_QUEENS), NB_QUEENS) +toolbox.register("permutation", random.sample, list(range(NB_QUEENS)), NB_QUEENS) #Structure initializers #An individual is a list that represents the position of each queen. diff --git a/examples/ga/nsga2.py b/examples/ga/nsga2.py index 4391390b2..77cb49ed6 100644 --- a/examples/ga/nsga2.py +++ b/examples/ga/nsga2.py @@ -88,7 +88,7 @@ def main(seed=None): record = stats.compile(pop) logbook.record(gen=0, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) # Begin the generational process for gen in range(1, NGEN): @@ -114,9 +114,9 @@ def main(seed=None): pop = toolbox.select(pop + offspring, MU) record = stats.compile(pop) logbook.record(gen=gen, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) - print("Final population hypervolume is %f" % hypervolume(pop, [11.0, 11.0])) + print(("Final population hypervolume is %f" % hypervolume(pop, [11.0, 11.0]))) return pop, logbook diff --git a/examples/ga/nsga3.py b/examples/ga/nsga3.py index 32b7410e1..e675e2ad8 100644 --- a/examples/ga/nsga3.py +++ b/examples/ga/nsga3.py @@ -81,7 +81,7 @@ def main(seed=None): # Compile statistics about the population record = stats.compile(pop) logbook.record(gen=0, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) # Begin the generational process for gen in range(1, NGEN): @@ -99,7 +99,7 @@ def main(seed=None): # Compile statistics about the new population record = stats.compile(pop) logbook.record(gen=gen, evals=len(invalid_ind), **record) - print(logbook.stream) + print((logbook.stream)) return pop, logbook @@ -109,7 +109,7 @@ def main(seed=None): pop_fit = numpy.array([ind.fitness.values for ind in pop]) pf = problem.pareto_front(ref_points) - print(igd(pop_fit, pf)) + print((igd(pop_fit, pf))) import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as Axes3d diff --git a/examples/ga/onemax.py b/examples/ga/onemax.py index 76882ef85..a4405c02f 100644 --- a/examples/ga/onemax.py +++ b/examples/ga/onemax.py @@ -89,7 +89,7 @@ def main(): for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit - print(" Evaluated %i individuals" % len(pop)) + print((" Evaluated %i individuals" % len(pop))) # Extracting all the fitnesses of fits = [ind.fitness.values[0] for ind in pop] @@ -101,7 +101,7 @@ def main(): while max(fits) < 100 and g < 1000: # A new generation g = g + 1 - print("-- Generation %i --" % g) + print(("-- Generation %i --" % g)) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) @@ -129,11 +129,11 @@ def main(): # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] - fitnesses = map(toolbox.evaluate, invalid_ind) + fitnesses = list(map(toolbox.evaluate, invalid_ind)) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit - print(" Evaluated %i individuals" % len(invalid_ind)) + print((" Evaluated %i individuals" % len(invalid_ind))) # The population is entirely replaced by the offspring pop[:] = offspring @@ -146,15 +146,15 @@ def main(): sum2 = sum(x*x for x in fits) std = abs(sum2 / length - mean**2)**0.5 - print(" Min %s" % min(fits)) - print(" Max %s" % max(fits)) - print(" Avg %s" % mean) - print(" Std %s" % std) + print((" Min %s" % min(fits))) + print((" Max %s" % max(fits))) + print((" Avg %s" % mean)) + print((" Std %s" % std)) print("-- End of (successful) evolution --") best_ind = tools.selBest(pop, 1)[0] - print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values)) + print(("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))) if __name__ == "__main__": main() diff --git a/examples/ga/onemax_island.py b/examples/ga/onemax_island.py index b14dd22ff..914744fea 100644 --- a/examples/ga/onemax_island.py +++ b/examples/ga/onemax_island.py @@ -109,12 +109,12 @@ def main(procid, pipein, pipeout, sync, seed=None): if procid == 0: # Synchronization needed to log header on top and only once - print(logbook.stream) + print((logbook.stream)) sync.set() else: logbook.log_header = False # Never output the header sync.wait() - print(logbook.stream) + print((logbook.stream)) for gen in range(1, NGEN): deme = toolbox.select(deme, len(deme)) @@ -127,7 +127,7 @@ def main(procid, pipein, pipeout, sync, seed=None): hof.update(deme) record = stats.compile(deme) logbook.record(gen=gen, deme=procid, evals=len(deme), **record) - print(logbook.stream) + print((logbook.stream)) if gen % MIG_RATE == 0 and gen > 0: toolbox.migrate(deme) diff --git a/examples/ga/onemax_multidemic.py b/examples/ga/onemax_multidemic.py index 673c4d418..ab086ae8c 100644 --- a/examples/ga/onemax_multidemic.py +++ b/examples/ga/onemax_multidemic.py @@ -73,7 +73,7 @@ def main(): ind.fitness.values = toolbox.evaluate(ind) logbook.record(gen=0, deme=idx, evals=len(deme), **stats.compile(deme)) hof.update(deme) - print(logbook.stream) + print((logbook.stream)) gen = 1 while gen <= NGEN and logbook[-1]["max"] < 100.0: @@ -87,7 +87,7 @@ def main(): logbook.record(gen=gen, deme=idx, evals=len(deme), **stats.compile(deme)) hof.update(deme) - print(logbook.stream) + print((logbook.stream)) if gen % MIG_RATE == 0: toolbox.migrate(demes) diff --git a/examples/ga/tsp.py b/examples/ga/tsp.py index 30fd449f7..3f362c311 100644 --- a/examples/ga/tsp.py +++ b/examples/ga/tsp.py @@ -38,7 +38,7 @@ toolbox = base.Toolbox() # Attribute generator -toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) +toolbox.register("indices", random.sample, list(range(IND_SIZE)), IND_SIZE) # Structure initializers toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices) diff --git a/examples/ga/xkcd.py b/examples/ga/xkcd.py index f1744be9c..41c6b6495 100644 --- a/examples/ga/xkcd.py +++ b/examples/ga/xkcd.py @@ -53,14 +53,14 @@ def evalXKCD(individual, target_price): taken by the order if the chef can cook everything in parallel.""" price = 0.0 times = list() - for item, number in individual.items(): + for item, number in list(individual.items()): price += ITEMS[item][0] * number times.append(ITEMS[item][1]) return abs(price - target_price), max(times) def cxCounter(ind1, ind2, indpb): """Swaps the number of perticular items between two individuals""" - for key in ITEMS.keys(): + for key in list(ITEMS.keys()): if random.random() < indpb: ind1[key], ind2[key] = ind2[key], ind1[key] return ind1, ind2 diff --git a/examples/gp/adf_symbreg.py b/examples/gp/adf_symbreg.py index c852f5cdb..886546e96 100644 --- a/examples/gp/adf_symbreg.py +++ b/examples/gp/adf_symbreg.py @@ -139,7 +139,7 @@ def main(): hof.update(pop) record = stats.compile(pop) logbook.record(gen=0, evals=len(pop), **record) - print(logbook.stream) + print((logbook.stream)) for g in range(1, NGEN): # Select the offspring @@ -171,9 +171,9 @@ def main(): hof.update(pop) record = stats.compile(pop) logbook.record(gen=g, evals=len(invalids), **record) - print(logbook.stream) + print((logbook.stream)) - print('Best individual : ', hof[0][0], hof[0].fitness) + print(('Best individual : ', hof[0][0], hof[0].fitness)) return pop, stats, hof diff --git a/examples/pso/basic.py b/examples/pso/basic.py index 1bfd85e9d..7c4ebe958 100644 --- a/examples/pso/basic.py +++ b/examples/pso/basic.py @@ -38,9 +38,9 @@ def generate(size, pmin, pmax, smin, smax): def updateParticle(part, best, phi1, phi2): u1 = (random.uniform(0, phi1) for _ in range(len(part))) u2 = (random.uniform(0, phi2) for _ in range(len(part))) - v_u1 = map(operator.mul, u1, map(operator.sub, part.best, part)) - v_u2 = map(operator.mul, u2, map(operator.sub, best, part)) - part.speed = list(map(operator.add, part.speed, map(operator.add, v_u1, v_u2))) + v_u1 = list(map(operator.mul, u1, list(map(operator.sub, part.best, part)))) + v_u2 = list(map(operator.mul, u2, list(map(operator.sub, best, part)))) + part.speed = list(map(operator.add, part.speed, list(map(operator.add, v_u1, v_u2)))) for i, speed in enumerate(part.speed): if abs(speed) < part.smin: part.speed[i] = math.copysign(part.smin, speed) @@ -82,7 +82,7 @@ def main(): # Gather all the fitnesses in one list and print the stats logbook.record(gen=g, evals=len(pop), **stats.compile(pop)) - print(logbook.stream) + print((logbook.stream)) return pop, logbook, best diff --git a/examples/pso/basic_numpy.py b/examples/pso/basic_numpy.py index 3aa266972..b67692884 100644 --- a/examples/pso/basic_numpy.py +++ b/examples/pso/basic_numpy.py @@ -81,7 +81,7 @@ def main(): # Gather all the fitnesses in one list and print the stats logbook.record(gen=g, evals=len(pop), **stats.compile(pop)) - print(logbook.stream) + print((logbook.stream)) return pop, logbook, best diff --git a/examples/pso/multiswarm.py b/examples/pso/multiswarm.py index a799d0a14..6201ace71 100644 --- a/examples/pso/multiswarm.py +++ b/examples/pso/multiswarm.py @@ -26,7 +26,7 @@ import numpy try: - from itertools import imap + except: # Python 3 nothing to do pass @@ -82,15 +82,15 @@ def convertQuantum(swarm, rcloud, centre, dist): def updateParticle(part, best, chi, c): ce1 = (c * random.uniform(0, 1) for _ in range(len(part))) ce2 = (c * random.uniform(0, 1) for _ in range(len(part))) - ce1_p = map(operator.mul, ce1, map(operator.sub, best, part)) - ce2_g = map(operator.mul, ce2, map(operator.sub, part.best, part)) - a = map(operator.sub, - map(operator.mul, + ce1_p = list(map(operator.mul, ce1, list(map(operator.sub, best, part)))) + ce2_g = list(map(operator.mul, ce2, list(map(operator.sub, part.best, part)))) + a = list(map(operator.sub, + list(map(operator.mul, itertools.repeat(chi), - map(operator.add, ce1_p, ce2_g)), - map(operator.mul, + list(map(operator.add, ce1_p, ce2_g)))), + list(map(operator.mul, itertools.repeat(1 - chi), - part.speed)) + part.speed)))) part.speed = list(map(operator.add, part.speed, a)) part[:] = list(map(operator.add, part, part.speed)) @@ -139,7 +139,7 @@ def main(verbose=True): error=mpb.currentError(), offline_error=mpb.offlineError(), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) generation = 1 while mpb.nevals < 5e5: @@ -197,11 +197,11 @@ def main(verbose=True): error=mpb.currentError(), offline_error=mpb.offlineError(), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Apply exclusion reinit_swarms = set() - for s1, s2 in itertools.combinations(range(len(population)), 2): + for s1, s2 in itertools.combinations(list(range(len(population))), 2): # Swarms must have a best and not already be set to reinitialize if population[s1].best and population[s2].best and not (s1 in reinit_swarms or s2 in reinit_swarms): dist = 0 diff --git a/examples/pso/speciation.py b/examples/pso/speciation.py index 3742a6405..6dc6183de 100644 --- a/examples/pso/speciation.py +++ b/examples/pso/speciation.py @@ -26,7 +26,7 @@ import numpy try: - from itertools import imap + except: # Python 3 nothing to do pass @@ -81,15 +81,15 @@ def convert_quantum(swarm, rcloud, centre): def updateParticle(part, best, chi, c): ce1 = (c*random.uniform(0, 1) for _ in range(len(part))) ce2 = (c*random.uniform(0, 1) for _ in range(len(part))) - ce1_p = map(operator.mul, ce1, map(operator.sub, best, part)) - ce2_g = map(operator.mul, ce2, map(operator.sub, part.best, part)) - a = map(operator.sub, - map(operator.mul, + ce1_p = list(map(operator.mul, ce1, list(map(operator.sub, best, part)))) + ce2_g = list(map(operator.mul, ce2, list(map(operator.sub, part.best, part)))) + a = list(map(operator.sub, + list(map(operator.mul, itertools.repeat(chi), - map(operator.add, ce1_p, ce2_g)), - map(operator.mul, + list(map(operator.add, ce1_p, ce2_g)))), + list(map(operator.mul, itertools.repeat(1-chi), - part.speed)) + part.speed)))) part.speed = list(map(operator.add, part.speed, a)) part[:] = list(map(operator.add, part, part.speed)) @@ -149,7 +149,7 @@ def main(verbose=True): error=mpb.currentError(), offline_error=mpb.offlineError(), **record) if verbose: - print(logbook.stream) + print((logbook.stream)) # Detect change if any(s[0].bestfit.values != toolbox.evaluate(s[0].best) for s in species): diff --git a/setup.py b/setup.py index 03dd3cd16..721f31c8d 100644 --- a/setup.py +++ b/setup.py @@ -87,24 +87,24 @@ def run_setup(build_ext): ext_modules=extra_modules, cmdclass={"build_ext": ve_build_ext}, install_requires=['numpy'], - use_2to3=True + use_2to3=False ) try: run_setup(True) except BuildFailed: - print("*" * 75) + print(("*" * 75)) print("WARNING: The C extensions could not be compiled, " "speedups won't be available.") print("Now building without C extensions.") - print("*" * 75) + print(("*" * 75)) run_setup(False) - print("*" * 75) + print(("*" * 75)) print("WARNING: The C extensions could not be compiled, " "speedups won't be available.") print("Plain-Python installation succeeded.") - print("*" * 75) + print(("*" * 75)) -print("\n".join(warnings)) +print(("\n".join(warnings)))