Skip to content

Commit

Permalink
Merge pull request #32 from aarongarrett/feat/2to3
Browse files Browse the repository at this point in the history
feat: run 2to3 to update code for py3
  • Loading branch information
sanjayankur31 authored Nov 2, 2023
2 parents 4bc3621 + 6581986 commit d5e2aec
Show file tree
Hide file tree
Showing 14 changed files with 246 additions and 261 deletions.
16 changes: 8 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@
master_doc = 'index'

# General information about the project.
project = u'inspyred'
copyright = u"2017, Aaron Garrett"
project = 'inspyred'
copyright = "2017, Aaron Garrett"

# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
Expand Down Expand Up @@ -209,8 +209,8 @@
# [howto/manual]).
latex_documents = [
('index', 'inspyred.tex',
u'inspyred Documentation',
u'Aaron Garrett', 'manual'),
'inspyred Documentation',
'Aaron Garrett', 'manual'),
]

# The name of an image file (relative to this directory) to place at
Expand Down Expand Up @@ -240,8 +240,8 @@
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'inspyred',
u'inspyred Documentation',
[u'Aaron Garrett'], 1)
'inspyred Documentation',
['Aaron Garrett'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -255,8 +255,8 @@
# dir menu entry, description, category)
texinfo_documents = [
('index', 'inspyred',
u'inspyred Documentation',
u'Aaron Garrett',
'inspyred Documentation',
'Aaron Garrett',
'inspyred',
'A framework for creating bio-inspired computational intelligence algorithms in Python.',
'Miscellaneous'),
Expand Down
4 changes: 2 additions & 2 deletions docs/moonshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
return zip(a, b)

def distance_between(position_a, position_b):
return math.sqrt((position_a[0] - position_b[0])**2 + (position_a[1] - position_b[1])**2)
Expand Down Expand Up @@ -147,7 +147,7 @@ def moonshot(orbital_height, satellite_mass, boost_velocity, initial_y_velocity,
x = [p[0] for p in position]
y = [p[1] for p in position]
cm = plt.get_cmap('gist_rainbow')
lines = plt.scatter(x, y, c=range(len(x)), cmap=cm, marker='o', s=2)
lines = plt.scatter(x, y, c=list(range(len(x))), cmap=cm, marker='o', s=2)
plt.setp(lines, edgecolors='None')
plt.axis("equal")
plt.grid("on")
Expand Down
4 changes: 2 additions & 2 deletions docs/polyarea.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from time import time
from time import sleep
import inspyred
from Tkinter import *
from tkinter import *
import itertools
#end_imports

Expand All @@ -12,7 +12,7 @@ def area(p):
return 0.5 * abs(sum([x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(p)]))

def segments(p):
return zip(p, p[1:] + [p[0]])
return list(zip(p, p[1:] + [p[0]]))

def generate_polygon(random, args):
size = args.get('num_vertices', 6)
Expand Down
2 changes: 1 addition & 1 deletion examples/custom/custom_variator_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
def my_variator(random, candidates, args):
mutants = []
for c in candidates:
points = random.sample(range(len(c)), 2)
points = random.sample(list(range(len(c))), 2)
x, y = min(points), max(points)
if x == 0:
mutants.append(c[y::-1] + c[y+1:])
Expand Down
16 changes: 8 additions & 8 deletions inspyred/benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def __init__(self, benchmark, dimension_bits):

def _binary_to_real(self, binary):
real = []
for d, lo, hi in zip(range(self.dimensions), self.benchmark.bounder.lower_bound, self.benchmark.bounder.upper_bound):
for d, lo, hi in zip(list(range(self.dimensions)), self.benchmark.bounder.lower_bound, self.benchmark.bounder.upper_bound):
b = binary[d*self.dimension_bits:(d+1)*self.dimension_bits]
real_val = float(int(''.join([str(i) for i in b]), 2))
value = real_val / (2**(self.dimension_bits)-1) * (hi - lo) + lo
Expand Down Expand Up @@ -513,7 +513,7 @@ def evaluator(self, candidates, args):
for c in candidates:
gval = g(c[self.objectives-1:])
fit = [0.5 * reduce(lambda x,y: x*y, c[:self.objectives-1]) * (1 + gval)]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
fit.append(0.5 * reduce(lambda x,y: x*y, c[:m-1], 1) * (1 - c[m-1]) * (1 + gval))
fitness.append(emo.Pareto(fit))
return fitness
Expand Down Expand Up @@ -573,7 +573,7 @@ def evaluator(self, candidates, args):
gval = g(c[self.objectives-1:])
fit = [(1 + gval) *
reduce(lambda x,y: x*y, [math.cos(a * math.pi / 2.0) for a in c[:self.objectives-1]])]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
fit.append((1 + gval) *
reduce(lambda x,y: x*y, [math.cos(a * math.pi / 2.0) for a in c[:m-1]], 1) *
math.sin(c[m-1] * math.pi / 2.0))
Expand Down Expand Up @@ -634,7 +634,7 @@ def evaluator(self, candidates, args):
for c in candidates:
gval = g(c[self.objectives-1:])
fit = [(1 + gval) * reduce(lambda x,y: x*y, [math.cos(a * math.pi / 2.0) for a in c[:self.objectives-1]])]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
fit.append((1 + gval) *
reduce(lambda x,y: x*y, [math.cos(a * math.pi / 2.0) for a in c[:m-1]], 1) *
math.sin(c[m-1] * math.pi / 2.0))
Expand Down Expand Up @@ -697,7 +697,7 @@ def evaluator(self, candidates, args):
gval = g(c[self.objectives-1:])
fit = [(1 + gval) *
reduce(lambda x,y: x*y, [math.cos(a**self.alpha * math.pi / 2.0) for a in c[:self.objectives-1]])]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
fit.append((1 + gval) *
reduce(lambda x,y: x*y, [math.cos(a**self.alpha * math.pi / 2.0) for a in c[:m-1]], 1) *
math.sin(c[m-1]**self.alpha * math.pi / 2.0))
Expand Down Expand Up @@ -782,7 +782,7 @@ def evaluator(self, candidates, args):
theta = lambda x: math.pi / (4.0 * (1 + gval)) * (1 + 2 * gval * x)
fit = [(1 + gval) * math.cos(math.pi / 2.0 * c[0]) *
reduce(lambda x,y: x*y, [math.cos(theta(a)) for a in c[1:self.objectives-1]])]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
if m == 1:
fit.append((1 + gval) * math.sin(math.pi / 2.0 * c[0]))
else:
Expand Down Expand Up @@ -849,7 +849,7 @@ def evaluator(self, candidates, args):
theta = lambda x: math.pi / (4.0 * (1 + gval)) * (1 + 2 * gval * x)
fit = [(1 + gval) * math.cos(math.pi / 2.0 * c[0]) *
reduce(lambda x,y: x*y, [math.cos(theta(a)) for a in c[1:self.objectives-1]])]
for m in reversed(range(1, self.objectives)):
for m in reversed(list(range(1, self.objectives))):
if m == 1:
fit.append((1 + gval) * math.sin(math.pi / 2.0 * c[0]))
else:
Expand Down Expand Up @@ -972,7 +972,7 @@ class TSP(Benchmark):
def __init__(self, weights):
Benchmark.__init__(self, len(weights))
self.weights = weights
self.components = [swarm.TrailComponent((i, j), value=(1 / weights[i][j])) for i, j in itertools.permutations(range(len(weights)), 2)]
self.components = [swarm.TrailComponent((i, j), value=(1 / weights[i][j])) for i, j in itertools.permutations(list(range(len(weights))), 2)]
self.bias = 0.5
self.bounder = ec.DiscreteBounder([i for i in range(len(weights))])
self.maximize = True
Expand Down
93 changes: 45 additions & 48 deletions inspyred/ec/evaluators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
===============================================
:mod:`evaluators` -- Fitness evaluation methods
===============================================
Evaluator functions are problem-specific. This module provides pre-defined
Evaluator functions are problem-specific. This module provides pre-defined
evaluators for evolutionary computations.
All evaluator functions have the following arguments:
- *candidates* -- the candidate solutions
- *args* -- a dictionary of keyword arguments
.. Copyright 2012 Aaron Garrett
.. Permission is hereby granted, free of charge, to any person obtaining a copy
Expand All @@ -29,43 +29,40 @@
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE.
.. module:: evaluators
.. moduleauthor:: Aaron Garrett <[email protected]>
.. moduleauthor:: Jelle Feringa <[email protected]>
"""
import functools
try:
import cPickle as pickle
except ImportError:
import pickle
import pickle


def evaluator(evaluate):
"""Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
fitness = evaluate(candidate, args)
This function is most commonly used as a function decorator with
the following usage::
@evaluator
def evaluate(candidate, args):
# Implementation of evaluation
pass
The generated function also contains an attribute named
``single_evaluation`` which holds the original evaluation function.
In this way, the original single-candidate function can be
retrieved if necessary.
"""
@functools.wraps(evaluate)
def inspyred_evaluator(candidates, args):
Expand All @@ -75,59 +72,59 @@ def inspyred_evaluator(candidates, args):
return fitness
inspyred_evaluator.single_evaluation = evaluate
return inspyred_evaluator


def parallel_evaluation_pp(candidates, args):
"""Evaluate the candidates in parallel using Parallel Python.
This function allows parallel evaluation of candidate solutions.
It uses the `Parallel Python <http://www.parallelpython.com>`_ (pp)
library to accomplish the parallelization. This library must already
be installed in order to use this function. The function assigns the
evaluation of each candidate to its own job, all of which are then
library to accomplish the parallelization. This library must already
be installed in order to use this function. The function assigns the
evaluation of each candidate to its own job, all of which are then
distributed to the available processing units.
.. note::
All arguments to the evaluation function must be pickleable.
Those that are not will not be sent through the ``args`` variable
and will be unavailable to your function.
.. Arguments:
candidates -- the candidate solutions
args -- a dictionary of keyword arguments
Required keyword arguments in args:
- *pp_evaluator* -- actual evaluation function to be used (This function
should have the same signature as any other inspyred evaluation function.)
Optional keyword arguments in args:
- *pp_dependencies* -- tuple of functional dependencies of the serial
- *pp_dependencies* -- tuple of functional dependencies of the serial
evaluator (default ())
- *pp_modules* -- tuple of modules that must be imported for the
- *pp_modules* -- tuple of modules that must be imported for the
functional dependencies (default ())
- *pp_servers* -- tuple of servers (on a cluster) that will be used
- *pp_servers* -- tuple of servers (on a cluster) that will be used
for parallel processing (default ("*",))
- *pp_secret* -- string representing the secret key needed to authenticate
on a worker node (default "inspyred")
- *pp_nprocs* -- integer representing the number of worker processes to
start on the local machine (default "autodetect", which sets it to the
number of processors in the system)
For more information about these arguments, please consult the
documentation for `Parallel Python <http://www.parallelpython.com>`_.
"""
import pp
logger = args['_ec'].logger

try:
evaluator = args['pp_evaluator']
except KeyError:
logger.error('parallel_evaluation_pp requires \'pp_evaluator\' be defined in the keyword arguments list')
raise
raise
secret_key = args.setdefault('pp_secret', 'inspyred')
try:
job_server = args['_pp_job_server']
Expand All @@ -138,7 +135,7 @@ def parallel_evaluation_pp(candidates, args):
args['_pp_job_server'] = job_server
pp_depends = args.setdefault('pp_dependencies', ())
pp_modules = args.setdefault('pp_modules', ())

pickled_args = {}
for key in args:
try:
Expand All @@ -147,10 +144,10 @@ def parallel_evaluation_pp(candidates, args):
except (TypeError, pickle.PickleError, pickle.PicklingError):
logger.debug('unable to pickle args parameter {0} in parallel_evaluation_pp'.format(key))
pass

func_template = pp.Template(job_server, evaluator, pp_depends, pp_modules)
jobs = [func_template.submit([c], pickled_args) for c in candidates]

fitness = []
for i, job in enumerate(jobs):
r = job()
Expand All @@ -166,46 +163,46 @@ def parallel_evaluation_mp(candidates, args):
"""Evaluate the candidates in parallel using ``multiprocessing``.
This function allows parallel evaluation of candidate solutions.
It uses the standard multiprocessing library to accomplish the
It uses the standard multiprocessing library to accomplish the
parallelization. The function assigns the evaluation of each
candidate to its own job, all of which are then distributed to the
available processing units.
.. note::
All arguments to the evaluation function must be pickleable.
Those that are not will not be sent through the ``args`` variable
and will be unavailable to your function.
.. Arguments:
candidates -- the candidate solutions
args -- a dictionary of keyword arguments
Required keyword arguments in args:
- *mp_evaluator* -- actual evaluation function to be used (This function
should have the same signature as any other inspyred evaluation function.)
Optional keyword arguments in args:
- *mp_nprocs* -- number of processors that will be used (default machine
- *mp_nprocs* -- number of processors that will be used (default machine
cpu count)
"""
import time
import multiprocessing
logger = args['_ec'].logger

try:
evaluator = args['mp_evaluator']
except KeyError:
logger.error('parallel_evaluation_mp requires \'mp_evaluator\' be defined in the keyword arguments list')
raise
raise
try:
nprocs = args['mp_nprocs']
except KeyError:
nprocs = multiprocessing.cpu_count()

pickled_args = {}
for key in args:
try:
Expand All @@ -228,4 +225,4 @@ def parallel_evaluation_mp(candidates, args):
else:
end = time.time()
logger.debug('completed parallel_evaluation_mp in {0} seconds'.format(end - start))

Loading

0 comments on commit d5e2aec

Please sign in to comment.