[ecspy] r128 committed - Added two new migrators....

2 views
Skip to first unread message

ec...@googlecode.com

unread,
Feb 5, 2012, 12:43:25 AM2/5/12
to ec...@googlegroups.com
Revision: 128
Author: aaron.lee.garrett
Date: Sat Feb 4 21:42:21 2012
Log: Added two new migrators.
Tweaked parallel_evaluation_mp to pass the pickle-able parts of the args
dictionary.
Removed the necessity of numpy from the screen and file observers (still
needed, along with matplotlib, for the plot observer).
Updated the documentation.
Automated the pypi package uploading.
Increased the version number to 1.1 because there were non-negligible
changes.
http://code.google.com/p/ecspy/source/detail?r=128

Added:
/trunk/build_distribution.sh
/trunk/get_requirements.sh
Modified:
/trunk/README.txt
/trunk/build_distribution.bat
/trunk/docs/conf.py
/trunk/docs/tutorial.rst
/trunk/ecspy/__init__.py
/trunk/ecspy/evaluators.py
/trunk/ecspy/migrators.py
/trunk/ecspy/observers.py
/trunk/pavement.py
/trunk/tests/example_tests.py
/trunk/tests/operator_tests.py

=======================================
--- /dev/null
+++ /trunk/build_distribution.sh Sat Feb 4 21:42:21 2012
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+paver sdist upload
+paver bdist_egg upload
+
+cd docs
+make latex
+cd _build/latex
+pdflatex ecspy.tex
+cd ../../..
+rm -R html/_images/math
+paver upload_docs --upload-dir html
+
=======================================
--- /dev/null
+++ /trunk/get_requirements.sh Sat Feb 4 21:42:21 2012
@@ -0,0 +1,4 @@
+apt-get install python-numpy
+apt-get install python-matplotlib
+pip install paver
+pip install sphinxcontrib-paverutils
=======================================
--- /trunk/README.txt Sun Aug 29 14:02:31 2010
+++ /trunk/README.txt Sat Feb 4 21:42:21 2012
@@ -12,10 +12,9 @@
Requirements
============

- * Requires at least Python 2.6.
- * Numpy is required if the screen or file observers are used.
- * Matplotlib is required if the line plot observer is used.
- * Parallel Python (pp) is required if parallel evaluation is used.
+ * Requires at least Python 2.6 (not compatible with Python 3+).
+ * Numpy and Matplotlib are required if the line plot observer is used.
+ * Parallel Python (pp) is required if parallel_evaluation_pp is used.

@@ -44,7 +43,7 @@

* evaluators.py -- defines useful evaluation schemes, such as parallel
evaluation

- * migrators.py -- defines a basic default migration which does nothing
+ * migrators.py -- defines a few built-in migrators, including migration
via network and migration among concurrent processes

* observers.py -- defines a few built-in observers, including screen,
file, and plotting observers

=======================================
--- /trunk/build_distribution.bat Wed Nov 30 17:57:33 2011
+++ /trunk/build_distribution.bat Sat Feb 4 21:42:21 2012
@@ -6,3 +6,4 @@
cd _build\latex
pdflatex ecspy.tex
cd ..\..\..
+
=======================================
--- /trunk/docs/conf.py Tue Dec 6 10:12:01 2011
+++ /trunk/docs/conf.py Sat Feb 4 21:42:21 2012
@@ -45,9 +45,9 @@
# built documents.
#
# The short X.Y version.
-version = '1.0'
+version = '1.1'
# The full version, including alpha/beta/rc tags.
-release = '1.0'
+release = '1.1'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
=======================================
--- /trunk/docs/tutorial.rst Fri Dec 16 10:33:02 2011
+++ /trunk/docs/tutorial.rst Sat Feb 4 21:42:21 2012
@@ -66,7 +66,7 @@
::

$ python rastrigin.py
- [1.00417551773511, 1.0001095903123427, 1.0001202435277237] :
0.00346400956156
+ [0.9996479288978145, 1.0011106329445922, 0.9993723649808806] :
0.000347459890914

.. {{{end}}}

=======================================
--- /trunk/ecspy/__init__.py Tue Dec 6 10:12:01 2011
+++ /trunk/ecspy/__init__.py Sat Feb 4 21:42:21 2012
@@ -17,9 +17,24 @@
along with this program. If not, see
<http://www.gnu.org/licenses/>.
"""

+import analysis
+import archivers
+import benchmarks
+import contrib
+import ec
+import emo
+import evaluators
+import migrators
+import observers
+import replacers
+import selectors
+import swarm
+import terminators
+import topologies
+import variators

__all__ =
['analysis', 'archivers', 'benchmarks', 'contrib', 'ec', 'emo', 'evaluators', 'migrators',
'observers', 'replacers', 'selectors', 'swarm', 'terminators', 'topologies', 'variators']
-__version__ = '1.0'
+__version__ = '1.1'
__author__ = 'Aaron Garrett <aaron.le...@gmail.com>'
__url__ = 'http://ecspy.googlecode.com'
=======================================
--- /trunk/ecspy/evaluators.py Sat Feb 4 13:47:24 2012
+++ /trunk/ecspy/evaluators.py Sat Feb 4 21:42:21 2012
@@ -24,6 +24,7 @@
along with this program. If not, see
<http://www.gnu.org/licenses/>.
"""

+import pickle

def evaluator(evaluate):
"""Return an ecspy evaluator function based on the given function.
@@ -119,7 +120,7 @@
job_server = args['_pp_job_server']
except KeyError:
pp_servers = args.get('pp_servers', ("*",))
- job_server = pp.Server(ppservers=pp_servers)
+ job_server = pp.Server(ppservers=pp_servers, secret="ecspy")
args['_pp_job_server'] = job_server
pp_depends = args.setdefault('pp_dependencies', ())
pp_modules = args.setdefault('pp_modules', ())
@@ -194,7 +195,7 @@
try:
pickle.dumps(args[key])
mp_args[key] = args[key]
- except TypeError, pickle.PickleError:
+ except (TypeError, pickle.PickleError, pickle.PicklingError):
logger.debug('in mp_evaluator: unable to pickle args
parameter %s' % key)
pass

=======================================
--- /trunk/ecspy/migrators.py Sun Jan 8 22:24:35 2012
+++ /trunk/ecspy/migrators.py Sat Feb 4 21:42:21 2012
@@ -25,8 +25,15 @@
along with this program. If not, see
<http://www.gnu.org/licenses/>.
"""

-import multiprocessing
+import sys
import Queue
+import socket
+import pickle
+import threading
+import collections
+import SocketServer
+import multiprocessing
+


def default_migration(random, population, args):
@@ -37,7 +44,7 @@
"""
return population

-
+
class MultiprocessingMigrator(object):
"""Migrate among processes on the same machine.

@@ -91,4 +98,119 @@
return population


-
+class NetworkMigrator(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
+ """Defines a migration function across a network.
+
+ This callable class acts as a migration function that
+ allows candidate solutions to migrate from one population
+ to another via TCP/IP connections.
+
+ The migrator is constructed by specifying the IP address
+ of the server (hosting the population from which individuals
+ emigrate) as an IP-port tuple and the addresses of the clients
+ (hosting the populations to which individuals from the server
+ immigrate) as a list of IP-port tuples. The ``max_migrants``
+ parameter specifies the size of the queue of migrants waiting
+ to immigrate to the server from the clients; the newest migrants
+ replace older ones in the queue.
+
+ Note: In order to use this migration operator, individuals
+ must be pickle-able.
+
+ The following is an example of the use of this operator::
+
+ m = NetworkMigrator(('192.168.1.10', 25125),
+ [('192.168.1.11', 12345), ('192.168.1.12',
54321)],
+ max_migrants=3)
+
+ Since the NetworkMigrator object is a server, it should always
+ call the ``shutdown()`` method when it is no longer needed, in
+ order to give back its resources.
+
+ Public Attributes:
+
+ - *client_addresses* -- the list of IP address tuples
+ (IP, port) to which individuals should migrate
+ - *migrants* -- the deque of migrants (of maximum size
+ specified by ``max_migrants``) waiting to immigrate
+ to client populations
+
+ """
+ def __init__(self, server_address, client_addresses, max_migrants=1):
+ SocketServer.TCPServer.__init__(self, server_address, None)
+ self.client_addresses = client_addresses
+ self.migrants = collections.deque(maxlen=max_migrants)
+ t = threading.Thread(target=self.serve_forever)
+ t.setDaemon(True)
+ t.start()
+
+ def finish_request(self, request, client_address):
+ try:
+ rbufsize = -1
+ wbufsize = 0
+ rfile = request.makefile('rb', rbufsize)
+ wfile = request.makefile('wb', wbufsize)
+
+ pickle_data = rfile.readline().strip()
+ migrant = pickle.loads(pickle_data)
+ self.migrants.append(migrant)
+
+ if not wfile.closed:
+ wfile.flush()
+ wfile.close()
+ rfile.close()
+ finally:
+ sys.exc_traceback = None
+
+ def __call__(self, random, population, args):
+ """Perform the migration.
+
+ This function serves as the migration operator. Here, a random
address
+ is chosen from the ``client_addresses`` list, and a random
individual
+ is chosen from the population to become the migrant. A socket is
opened
+ to the chosen client address, and the chosen migrant is pickled and
+ sent to the NetworkMigrator object running at the client address.
Then
+ the migrant queue on the current machine is queried for a migrant
+ to replace the one sent. If one is found, it replaces the newly
+ migrated individual; otherwise, the individual remains in the
population.
+
+ Any immigrants may also be re-evaluated before insertion into the
+ current population by setting the ``evaluate_migrant`` keyword
+ argument in ``args`` to True. This is useful if the evaluation
+ functions in different populations are different and we want to
compare
+ "apples to apples," as they say.
+
+ Arguments:
+
+ - *random* -- the random number generator object
+ - *population* -- the population of Individuals
+ - *args* -- a dictionary of keyword arguments
+
+ Optional keyword arguments in the ``args`` parameter:
+
+ - *evaluate_migrant* -- whether to re-evaluate the immigrant
(default False)
+
+ """
+ evaluate_migrant = args.setdefault('evaluate_migrant', False)
+ client_address = random.choice(self.client_addresses)
+ migrant_index = random.randint(0, len(population) - 1)
+ pickle_data = pickle.dumps(population[migrant_index])
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ sock.connect(client_address)
+ sock.send(pickle_data + '\n')
+ finally:
+ sock.close()
+ if len(self.migrants) > 0:
+ migrant = self.migrants.popleft()
+ if evaluate_migrant:
+ fit = args._ec.evaluator([migrant], args)
+ migrant.fitness = fit[0]
+ args._ec.num_evaluations += 1
+ population[migrant_index] = migrant
+ return population
+
+ def __str__(self):
+ return str(self.migrants)
+
+
=======================================
--- /trunk/ecspy/observers.py Fri Jan 20 05:52:17 2012
+++ /trunk/ecspy/observers.py Sat Feb 4 21:42:21 2012
@@ -48,16 +48,20 @@
args -- a dictionary of keyword arguments

"""
- import numpy
-
+
population = list(population)
population.sort(reverse=True)
worst_fit = population[-1].fitness
best_fit = population[0].fitness
- med_fit = numpy.median([p.fitness for p in population])
- avg_fit = numpy.mean([p.fitness for p in population])
- std_fit = numpy.std([p.fitness for p in population], ddof=1)
-
+
+ plen = len(population)
+ if plen % 2 == 1:
+ med_fit = population[(plen - 1) / 2].fitness
+ else:
+ med_fit = float(population[plen / 2 - 1].fitness + population[plen
/ 2].fitness) / 2
+ avg_fit = sum([p.fitness for p in population]) / float(plen)
+ std_fit = math.sqrt(sum([(p.fitness - avg_fit)**2 for p in
population]) / float(plen - 1))
+
print('Generation Evaluation Worst Best Median
Average Std Dev ')
print('---------- ---------- ---------- ---------- ----------
---------- ----------')
print('{0:10} {1:10} {2:10} {3:10} {4:10} {5:10}
{6:10}\n'.format(num_generations, num_evaluations, worst_fit, best_fit,
med_fit, avg_fit, std_fit))
@@ -92,9 +96,6 @@
- *individuals_file* -- a file object (default: see text)

"""
- # Import the necessary libraries here. Otherwise, they would have to be
- # installed even if this function is not called.
- import numpy

try:
statistics_file = args['statistics_file']
@@ -109,9 +110,15 @@
population.sort(reverse=True)
worst_fit = population[-1].fitness
best_fit = population[0].fitness
- med_fit = numpy.median([p.fitness for p in population])
- avg_fit = numpy.mean([p.fitness for p in population])
- std_fit = numpy.std([p.fitness for p in population], ddof=1)
+
+ plen = len(population)
+ if plen % 2 == 1:
+ med_fit = population[(plen - 1) / 2].fitness
+ else:
+ med_fit = float(population[plen / 2 - 1].fitness + population[plen
/ 2].fitness) / 2
+ avg_fit = sum([p.fitness for p in population]) / float(plen)
+ std_fit = math.sqrt(sum([(p.fitness - avg_fit)**2 for p in
population]) / float(plen - 1))
+
statistics_file.write('{0}, {1}, {2}, {3}, {4}, {5},
{6}\n'.format(num_generations, len(population), worst_fit, best_fit,
med_fit, avg_fit, std_fit))
for i, p in enumerate(population):
individuals_file.write('{0}, {1}, {2},
{3}\n'.format(num_generations, i, p.fitness, str(p.candidate)))
=======================================
--- /trunk/pavement.py Tue Dec 6 10:12:01 2011
+++ /trunk/pavement.py Sat Feb 4 21:42:21 2012
@@ -1,3 +1,5 @@
+#!/usr/bin/python2.6
+
# Standard library
import os
import sys
@@ -17,7 +19,7 @@


PROJECT = 'ecspy'
-VERSION = '1.0'
+VERSION = '1.1'

# The sphinx templates expect the VERSION in the shell environment
os.environ['VERSION'] = VERSION
@@ -42,7 +44,7 @@
author='Aaron Garrett',
author_email='aaron.le...@gmail.com',
url='http://%s.googlecode.com' % PROJECT,
- download_url = 'http://%s.googlecode.com/files/%s-%s.zip' %
(PROJECT, PROJECT, VERSION),
+ download_url = 'http://%s.googlecode.com/files/%s-%s.tar.gz' %
(PROJECT, PROJECT, VERSION),
license='GPLv3+',
platforms=('Any'),

keywords=('python', 'optimization', 'evolutionary', 'computation', 'genetic
algorithm',
=======================================
--- /trunk/tests/example_tests.py Sun Aug 29 14:02:31 2010
+++ /trunk/tests/example_tests.py Sat Feb 4 21:42:21 2012
@@ -1,4 +1,4 @@
-import psyco; psyco.full()
+#import psyco; psyco.full()
import unittest, sys, os, random
pth = os.path.split( os.path.split( os.path.abspath(__file__) )[0] )[0]
sys.path.append( pth )
=======================================
--- /trunk/tests/operator_tests.py Sun Aug 22 00:13:44 2010
+++ /trunk/tests/operator_tests.py Sat Feb 4 21:42:21 2012
@@ -3,15 +3,7 @@
import random
import logging
import itertools
-from ecspy import ec
-from ecspy import emo
-from ecspy import archivers
-from ecspy import evaluators
-from ecspy import migrators
-from ecspy import replacers
-from ecspy import selectors
-from ecspy import terminators
-from ecspy import variators
+import ecspy


def test_generator(random, args):
@@ -26,7 +18,7 @@
def test_multiobjective_evaluator(candidates, args):
fitness = []
for c in candidates:
- fitness.append(emo.Pareto([sum(c), sum(c)]))
+ fitness.append(ecspy.emo.Pareto([sum(c), sum(c)]))
return fitness

prng = random.Random()
@@ -34,8 +26,8 @@
test_candidates = [test_generator(prng, {}) for _ in range(12)]
test_fitnesses = test_evaluator(test_candidates, {})
test_multiobjective_fitnesses =
test_multiobjective_evaluator(test_candidates, {})
-test_population = [ec.Individual(candidate=c) for c in test_candidates]
-test_multiobjective_population = [ec.Individual(candidate=c) for c in
test_candidates]
+test_population = [ecspy.ec.Individual(candidate=c) for c in
test_candidates]
+test_multiobjective_population = [ecspy.ec.Individual(candidate=c) for c
in test_candidates]
for i, f in zip(test_population, test_fitnesses):
i.fitness = f
test_parents = test_population[:6]
@@ -48,15 +40,15 @@

class ArchiverTests(unittest.TestCase):
def test_default_archiver(self):
- new_archive = archivers.default_archiver(prng, test_population,
[], {})
+ new_archive = ecspy.archivers.default_archiver(prng,
test_population, [], {})
assert new_archive == test_population

def test_best_archiver(self):
- new_archive = archivers.best_archiver(prng, test_population, [],
{})
+ new_archive = ecspy.archivers.best_archiver(prng, test_population,
[], {})
assert new_archive == [max(test_population)]

def test_adaptive_grid_archiver(self):
- new_archive = archivers.adaptive_grid_archiver(prng,
test_multiobjective_population, [], {})
+ new_archive = ecspy.archivers.adaptive_grid_archiver(prng,
test_multiobjective_population, [], {})
assert len(new_archive) == 1

class EvaluatorTests(unittest.TestCase):
@@ -65,7 +57,7 @@
def __init__(self):
self.logger = logging.getLogger('ecspy.test')
x = fake_ec()
- fitnesses = evaluators.parallel_evaluation_pp(test_candidates,
{'_ec':x, 'pp_evaluator':test_evaluator})
+ fitnesses =
ecspy.evaluators.parallel_evaluation_pp(test_candidates,
{'_ec':x, 'pp_evaluator':test_evaluator})
assert fitnesses == test_fitnesses

def test_parallel_evaluation_mp(self):
@@ -73,45 +65,45 @@
def __init__(self):
self.logger = logging.getLogger('ecspy.test')
x = fake_ec()
- fitnesses = evaluators.parallel_evaluation_mp(test_candidates,
{'_ec':x, 'mp_evaluator':test_evaluator})
+ fitnesses =
ecspy.evaluators.parallel_evaluation_mp(test_candidates,
{'_ec':x, 'mp_evaluator':test_evaluator})
assert fitnesses == test_fitnesses

class MigratorTests(unittest.TestCase):
def test_default_migration(self):
- migrants = migrators.default_migration(prng, test_population, {})
+ migrants = ecspy.migrators.default_migration(prng,
test_population, {})
assert migrants == test_population

class ReplacerTests(unittest.TestCase):
def test_default_replacement(self):
- survivors = replacers.default_replacement(prng, test_population,
test_parents, test_offspring, {})
+ survivors = ecspy.replacers.default_replacement(prng,
test_population, test_parents, test_offspring, {})
assert survivors == test_offspring

def test_truncation_replacement(self):
- survivors = replacers.truncation_replacement(prng,
test_population, test_parents, test_offspring, {})
+ survivors = ecspy.replacers.truncation_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == len(test_population) and
max(max(test_population), max(test_offspring)) == max(survivors)

def test_steady_state_replacement(self):
- survivors = replacers.steady_state_replacement(prng,
test_population, test_parents, test_offspring, {})
+ survivors = ecspy.replacers.steady_state_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == len(test_population) and all([o in
survivors for o in test_offspring])

def test_generational_replacement(self):
- survivors = replacers.generational_replacement(prng,
test_population, test_parents, test_offspring, {})
+ survivors = ecspy.replacers.generational_replacement(prng,
test_population, test_parents, test_offspring, {})
assert all([s in test_offspring for s in survivors])

def test_random_replacement(self):
- survivors = replacers.random_replacement(prng, test_population,
test_parents, test_offspring, {})
+ survivors = ecspy.replacers.random_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == len(test_population) and all([o in
survivors for o in test_offspring])

def test_plus_replacement(self):
- survivors = replacers.plus_replacement(prng, test_population,
test_parents, test_offspring, {})
+ survivors = ecspy.replacers.plus_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == len(test_population) and
max(max(test_parents), max(test_offspring)) == max(survivors)

def test_comma_replacement(self):
- survivors = replacers.comma_replacement(prng, test_population,
test_parents, test_offspring, {})
+ survivors = ecspy.replacers.comma_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == min(len(test_population),
len(test_offspring)) and all([s in test_offspring for s in survivors])

def test_crowding_replacement(self):
- survivors = replacers.crowding_replacement(prng, test_population,
test_parents, test_offspring, {})
+ survivors = ecspy.replacers.crowding_replacement(prng,
test_population, test_parents, test_offspring, {})
assert len(survivors) == len(test_population) and
max(max(test_population), max(test_offspring)) == max(survivors)

def test_simulated_annealing_replacement(self):
@@ -119,12 +111,12 @@
def __init__(self):
self.num_evaluations = 10
x = fake_ec()
- survivors = replacers.simulated_annealing_replacement(prng,
test_population, test_parents, test_offspring,
-
{'_ec':x, 'max_evaluations':100})
+ survivors = ecspy.replacers.simulated_annealing_replacement(prng,
test_population, test_parents, test_offspring,
+
{'_ec':x, 'max_evaluations':100})
assert len(survivors) == len(test_parents) and
max(max(test_parents), max(test_offspring)) == max(survivors)

def test_nsga_replacement(self):
- survivors = replacers.nsga_replacement(prng,
test_multiobjective_population, test_multiobjective_parents,
test_multiobjective_offspring, {})
+ survivors = ecspy.replacers.nsga_replacement(prng,
test_multiobjective_population, test_multiobjective_parents,
test_multiobjective_offspring, {})
assert (len(survivors) == len(test_multiobjective_population) and
max(max(test_multiobjective_population),
max(test_multiobjective_offspring)) == max(survivors))

@@ -132,61 +124,61 @@
class fake_ec(object):
def __init__(self):
self.archive = []
- self.archiver = archivers.adaptive_grid_archiver
+ self.archiver = ecspy.archivers.adaptive_grid_archiver
x = fake_ec()
- survivors = replacers.paes_replacement(prng,
test_multiobjective_population, test_multiobjective_parents,
-
test_multiobjective_offspring, {'_ec':x})
+ survivors = ecspy.replacers.paes_replacement(prng,
test_multiobjective_population, test_multiobjective_parents,
+
test_multiobjective_offspring, {'_ec':x})
assert (len(survivors) == min(len(test_multiobjective_parents),
len(test_multiobjective_offspring)) and
max(survivors) == max(max(test_multiobjective_parents),
max(test_multiobjective_offspring)))

class SelectorTests(unittest.TestCase):
def test_default_selection(self):
- parents = selectors.default_selection(prng, test_population, {})
+ parents = ecspy.selectors.default_selection(prng, test_population,
{})
assert parents == test_population

def test_truncation_selection(self):
- parents = selectors.truncation_selection(prng, test_population, {})
+ parents = ecspy.selectors.truncation_selection(prng,
test_population, {})
assert all([p in parents for p in test_population])

def test_uniform_selection(self):
- parents = selectors.uniform_selection(prng, test_population, {})
+ parents = ecspy.selectors.uniform_selection(prng, test_population,
{})
assert len(parents) == 1 and all([p in test_population for p in
parents])

def test_fitness_proportionate_selection(self):
- parents = selectors.fitness_proportionate_selection(prng,
test_population, {})
+ parents = ecspy.selectors.fitness_proportionate_selection(prng,
test_population, {})
assert len(parents) == 1 and all([p in test_population for p in
parents])

def test_rank_selection(self):
- parents = selectors.rank_selection(prng, test_population, {})
+ parents = ecspy.selectors.rank_selection(prng, test_population, {})
assert len(parents) == 1 and all([p in test_population for p in
parents])

def test_tournament_selection(self):
- parents = selectors.tournament_selection(prng, test_population,
{'tourn_size':len(test_population)})
+ parents = ecspy.selectors.tournament_selection(prng,
test_population, {'tourn_size':len(test_population)})
assert len(parents) == 1 and max(parents) == max(test_population)

class TerminatorTests(unittest.TestCase):
def test_default_termination(self):
- t = terminators.default_termination(test_population, 1, 1, {})
+ t = ecspy.terminators.default_termination(test_population, 1, 1,
{})
assert t == True

def test_diversity_termination(self):
- p = [ec.Individual(candidate=[1, 1, 1]) for _ in range(10)]
- t = terminators.diversity_termination(p, 1, 1, {})
+ p = [ecspy.ec.Individual(candidate=[1, 1, 1]) for _ in range(10)]
+ t = ecspy.terminators.diversity_termination(p, 1, 1, {})
assert t == True

def test_average_fitness_termination(self):
- p = [ec.Individual(candidate=i.candidate) for i in test_population]
+ p = [ecspy.ec.Individual(candidate=i.candidate) for i in
test_population]
for x in p:
x.fitness = 1
- t = terminators.average_fitness_termination(p, 1, 1, {})
+ t = ecspy.terminators.average_fitness_termination(p, 1, 1, {})
assert t == True

def test_evaluation_termination(self):
- t = terminators.evaluation_termination(test_population, 1,
len(test_population), {})
+ t = ecspy.terminators.evaluation_termination(test_population, 1,
len(test_population), {})
assert t == True

def test_generation_termination(self):
- t = terminators.generation_termination(test_population, 1, 1, {})
+ t = ecspy.terminators.generation_termination(test_population, 1,
1, {})
assert t == True

def test_time_termination(self):
@@ -194,25 +186,25 @@
def __init__(self):
self.logger = logging.getLogger('ecspy.test')
x = fake_ec()
- t = terminators.time_termination(test_population, 1, 1,
{'_ec':x, 'max_time':0})
+ t = ecspy.terminators.time_termination(test_population, 1, 1,
{'_ec':x, 'max_time':0})
assert t == True

class VariatorTests(unittest.TestCase):
def test_default_variation(self):
- offspring = variators.default_variation(prng,
list(test_candidates), {})
+ offspring = ecspy.variators.default_variation(prng,
list(test_candidates), {})
assert offspring == test_candidates

def test_estimation_of_distribution_variation(self):
class fake_ec(object):
def __init__(self):
- self.bounder = ec.Bounder()
+ self.bounder = ecspy.ec.Bounder()
x = fake_ec()
test_candidates = [[1] * 6 for _ in range(10)]
- offspring = variators.estimation_of_distribution_variation(prng,
list(test_candidates), {'_ec':x})
+ offspring =
ecspy.variators.estimation_of_distribution_variation(prng,
list(test_candidates), {'_ec':x})
assert len(offspring) == 1 and offspring[0] == test_candidates[0]

def test_n_point_crossover(self):
- offspring = variators.n_point_crossover(prng,
list(test_candidates), {'num_crossover_points':3})
+ offspring = ecspy.variators.n_point_crossover(prng,
list(test_candidates), {'num_crossover_points':3})
moms = test_candidates[::2]
dads = test_candidates[1::2]
dmoms = itertools.chain.from_iterable([[t, t] for t in moms])
@@ -222,7 +214,7 @@
all([(x in o[0] or x in o[1]) and (y in o[0] or y in o[1])
for m, d, o in zip(moms, dads, offs) for x in m for y in m]))

def test_uniform_crossover(self):
- offspring = variators.uniform_crossover(prng,
list(test_candidates), {})
+ offspring = ecspy.variators.uniform_crossover(prng,
list(test_candidates), {})
moms = test_candidates[::2]
dads = test_candidates[1::2]
dmoms = itertools.chain.from_iterable([[t, t] for t in moms])
@@ -234,10 +226,10 @@
def test_blend_crossover(self):
class fake_ec(object):
def __init__(self):
- self.bounder = ec.Bounder()
+ self.bounder = ecspy.ec.Bounder()
x = fake_ec()
alpha = 0.1
- offspring = variators.blend_crossover(prng, list(test_candidates),
{'_ec':x, 'blx_alpha':alpha})
+ offspring = ecspy.variators.blend_crossover(prng,
list(test_candidates), {'_ec':x, 'blx_alpha':alpha})
moms = itertools.chain.from_iterable([[t, t] for t in
test_candidates[::2]])
dads = itertools.chain.from_iterable([[t, t] for t in
test_candidates[1::2]])
tests = []
@@ -250,10 +242,10 @@
def test_differential_crossover(self):
class fake_ec(object):
def __init__(self):
- self.bounder = ec.Bounder()
+ self.bounder = ecspy.ec.Bounder()
self.population = list(test_population)
x = fake_ec()
- offspring = variators.differential_crossover(prng,
list(test_candidates), {'_ec':x})
+ offspring = ecspy.variators.differential_crossover(prng,
list(test_candidates), {'_ec':x})
moms = itertools.chain.from_iterable([[t, t] for t in
test_candidates[::2]])
dads = itertools.chain.from_iterable([[t, t] for t in
test_candidates[1::2]])
tests = []
@@ -271,9 +263,9 @@
def test_gaussian_mutation(self):
class fake_ec(object):
def __init__(self):
- self.bounder = ec.Bounder(0, 1)
+ self.bounder = ecspy.ec.Bounder(0, 1)
x = fake_ec()
- offspring = variators.gaussian_mutation(prng,
list(test_candidates), {'_ec':x})
+ offspring = ecspy.variators.gaussian_mutation(prng,
list(test_candidates), {'_ec':x})
assert([x >= 0 and x <= 1 for o in offspring for x in o])

def test_bit_flip_mutation(self):

Reply all
Reply to author
Forward
0 new messages