Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2to3 and parameter specific mutation rate #623

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions deap/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import random

import tools
from . import tools


def varAnd(population, toolbox, cxpb, mutpb):
Expand Down Expand Up @@ -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):
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand All @@ -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

Expand Down Expand Up @@ -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):
Expand All @@ -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


Expand Down Expand Up @@ -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
Expand All @@ -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
11 changes: 5 additions & 6 deletions deap/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ()
Expand Down
6 changes: 3 additions & 3 deletions deap/benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
22 changes: 11 additions & 11 deletions deap/benchmarks/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# You should have received a copy of the GNU Lesser General Public
# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.

from __future__ import division

from functools import wraps
import math

Expand All @@ -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)
Expand Down Expand Up @@ -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,

Expand All @@ -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,

Expand All @@ -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,
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions deap/benchmarks/movingpeaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
2 changes: 1 addition & 1 deletion deap/benchmarks/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions deap/cma.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from math import sqrt, log, exp
import numpy

import tools
from . import tools


class Strategy(object):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions deap/creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def __init__(self):

dict_inst = {}
dict_cls = {}
for obj_name, obj in kargs.iteritems():
for obj_name, obj in list(kargs.items()):
if isinstance(obj, type):
dict_inst[obj_name] = obj
else:
Expand All @@ -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 list(dict_inst.items()):
setattr(self, obj_name, obj())
if base.__init__ is not object.__init__:
base.__init__(self, *args, **kargs)
Expand Down
34 changes: 17 additions & 17 deletions deap/gp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 #
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand All @@ -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})
Expand Down Expand Up @@ -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)
Expand All @@ -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))
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -1191,7 +1191,7 @@ def graph(expr):
<http://networkx.lanl.gov/pygraphviz/>`_ as the nodes might be plotted
out of order when using `NetworX <http://networkx.github.com/>`_.
"""
nodes = range(len(expr))
nodes = list(range(len(expr)))
edges = list()
labels = dict()

Expand Down
Loading