[ecspy] r131 committed - Lots of changes. This is not a stable version yet.

4 views
Skip to first unread message

ec...@googlecode.com

unread,
Feb 8, 2012, 8:17:30 PM2/8/12
to ec...@googlegroups.com
Revision: 131
Author: aaron.lee.garrett
Date: Wed Feb 8 17:16:16 2012
Log: Lots of changes. This is not a stable version yet.
http://code.google.com/p/ecspy/source/detail?r=131

Added:
/trunk/examples/custom_archiver_example.py
/trunk/examples/custom_migrator_example.py
/trunk/examples/custom_observer_example.py
/trunk/examples/email_observer_example.py
/trunk/examples/niche_example.pdf
/trunk/examples/parallel_evaluation_mp_example.py
/trunk/examples/parallel_evaluation_pp_example.py
/trunk/tests/test_migrator.py
Modified:
/trunk/docs/conf.py
/trunk/docs/examples.rst
/trunk/docs/moonshot.py
/trunk/docs/polyarea.py
/trunk/docs/tutorial.rst
/trunk/ecspy/contrib/approximate.py
/trunk/ecspy/contrib/micro.py
/trunk/ecspy/ec.py
/trunk/ecspy/migrators.py
/trunk/ecspy/observers.py
/trunk/ecspy/replacers.py
/trunk/examples/constraint_example.py
/trunk/examples/custom_ec_example.py
/trunk/examples/dea_example.py
/trunk/examples/eda_example.py
/trunk/examples/es_example.py
/trunk/examples/ga_example.py
/trunk/examples/niche_example.py
/trunk/examples/nsga_example.py
/trunk/examples/paes_example.py
/trunk/examples/pso_example.py
/trunk/examples/sa_example.py
/trunk/tests/operator_tests.py

=======================================
--- /dev/null
+++ /trunk/examples/custom_archiver_example.py Wed Feb 8 17:16:16 2012
@@ -0,0 +1,34 @@
+from random import Random
+from time import time
+import ecspy
+
+def my_archiver(random, population, archive, args):
+ worst_in_pop = min(population)
+ if len(archive) > 0:
+ worst_in_arc = min(archive)
+ if worst_in_pop < worst_in_arc:
+ return [worst_in_pop]
+ else:
+ return archive
+ else:
+ return [worst_in_pop]
+
+if __name__ == '__main__':
+ prng = Random()
+ prng.seed(time())
+
+ problem = ecspy.benchmarks.Rosenbrock(2)
+ ea = ecspy.ec.ES(prng)
+ ea.observer = [ecspy.observers.stats_observer,
ecspy.observers.archive_observer]
+ ea.archiver = my_archiver
+ ea.terminator = ecspy.terminators.evaluation_termination
+ final_pop = ea.evolve(generator=problem.generator,
+ evaluator=problem.evaluator,
+ pop_size=100,
+ bounder=problem.bounder,
+ maximize=problem.maximize,
+ max_evaluations=30000,
+ mutation_rate=0.2,
+ use_one_fifth_rule=True)
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
=======================================
--- /dev/null
+++ /trunk/examples/custom_migrator_example.py Wed Feb 8 17:16:16 2012
@@ -0,0 +1,121 @@
+import sys
+import socket
+import pickle
+import threading
+import collections
+import SocketServer
+
+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)
=======================================
--- /dev/null
+++ /trunk/examples/custom_observer_example.py Wed Feb 8 17:16:16 2012
@@ -0,0 +1,26 @@
+from random import Random
+from time import time
+import ecspy
+
+def my_observer(population, num_generations, num_evaluations, args):
+ best = max(pop)
+ print("%6d -- %f : %s" % (num_generations, best.fitness,
str(best.candidate)))
+
+if __name__ == '__main__':
+ prng = Random()
+ prng.seed(time())
+
+ problem = ecspy.benchmarks.Rosenbrock(2)
+ ea = ecspy.ec.ES(prng)
+ ea.observer = my_observer
+ ea.terminator = ecspy.terminators.evaluation_termination
+ final_pop = ea.evolve(generator=problem.generator,
+ evaluator=problem.evaluator,
+ pop_size=100,
+ bounder=problem.bounder,
+ maximize=problem.maximize,
+ max_evaluations=30000,
+ mutation_rate=0.2,
+ use_one_fifth_rule=True)
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
=======================================
--- /dev/null
+++ /trunk/examples/email_observer_example.py Wed Feb 8 17:16:16 2012
@@ -0,0 +1,88 @@
+import smtplib
+from email.MIMEMultipart import MIMEMultipart
+from email.MIMEBase import MIMEBase
+from email.MIMEText import MIMEText
+from email import Encoders
+import getpass
+import os
+
+class EmailObserver(object):
+ def __init__(self, username, password, server, port=587):
+ self.username = username
+ self.password = password
+ self.server = server
+ self.port = port
+ self.subject = "ECsPy observer report"
+
+ def _send_mail(self, fromaddr, toaddr, subject, text,
attachments=None):
+ msg = MIMEMultipart()
+ msg['From'] = "ECsPy"
+ msg['To'] = toaddr
+ msg['Subject'] = subject
+ msg.attach(MIMEText(text))
+ part = MIMEBase('application', 'octet-stream')
+ if attachments is not None:
+ if not isinstance(attachments, (list, tuple)):
+ attachments = [attachments]
+ for file in attachments:
+ part.set_payload(open(file, 'rb').read())
+ Encoders.encode_base64(part)
+ part.add_header('Content-Disposition', 'attachment;
filename="%s"' % os.path.basename(file))
+ msg.attach(part)
+ mail_server = smtplib.SMTP(self.server, self.port)
+ mail_server.ehlo()
+ mail_server.starttls()
+ mail_server.ehlo()
+ mail_server.login(self.username, self.password)
+ mail_server.sendmail(fromaddr, toaddr, msg.as_string())
+ mail_server.quit()
+
+ def __call__(self, population, num_generations, num_evaluations, args):
+ population = list(population)
+ population.sort(reverse=True)
+ worst_fit = population[-1].fitness
+ best_fit = population[0].fitness
+
+ 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))
+
+ body = 'Generation Evaluation Worst Best Median
Average Std Dev \n'
+ body += '---------- ---------- ---------- ---------- ----------
---------- ----------\n'
+ body += '{0:10} {1:10} {2:10.5} {3:10.5} {4:10.5} {5:10.5}
{6:10.5}\n'.format(num_generations, num_evaluations, worst_fit, best_fit,
med_fit, avg_fit, std_fit)
+ body
+= '----------------------------------------------------------------------------\n'
+ for p in population:
+ body += p + '\n'
+ body
+= '----------------------------------------------------------------------------\n'
+ files = []
+ stats = args.getdefault("statistics_file", None)
+ inds = args.getdefault("individuals_file", None)
+ if stats is not None:
+ files.append(stats.name)
+ if inds is not None:
+ files.append(inds.name)
+ self._send_mail(self.from_address, self.to_address, self.subject,
body, files)
+
+
+if __name__ == '__main__':
+ import getpass
+ usr = raw_input("Enter your username: ")
+ pwd = getpass.getpass("Enter your password: ")
+ email_observer = EmailObserver(usr, pwd, "my.mail.server")
+ email_observer.from_address = "m...@here.com"
+ email_observer.to_address = "y...@there.com"
+
+
+
+
+
+
+
+
+
+
+
=======================================
--- /dev/null
+++ /trunk/examples/niche_example.pdf Wed Feb 8 17:16:16 2012
@@ -0,0 +1,358 @@
+%PDF-1.4
+%† Ǽ
+1 0 obj
+<< /Type /Catalog /Pages 2 0 R >>
+endobj
+8 0 obj
+<< /XObject 7 0 R /Pattern 5 0 R
+/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /ExtGState 4 0 R
+/Shading 6 0 R /Font 3 0 R >>
+endobj
+10 0 obj
+<< /Contents 9 0 R /Type /Page /Resources 8 0 R /Parent 2 0 R
+/MediaBox [ 0 0 576 432 ] >>
+endobj
+9 0 obj
+<< /Filter /FlateDecode /Length 11 0 R >>
+stream
+xœ}œÉ®%9n†÷ñ gi/|¬yØ ° è Û ø Ò Œ, ö¦_ßßO)Î
+I·²³»«2
+Q ‡Ÿ uü뿯ðúóË¿þ“ÿýér/÷úý•káŸ?íŸ) þÍÍ þ×õ ¼óWþþ§«
+¾ƒÞ÷í Æ_~οÄÖÞ ¿ñÒý¯ÿuýÇõ¿¯{TJE¯¥ü.¯ÿû÷׿¾þ‡ Š ±ð âæ¯ó/ ùÓ }z× ‹K¹äòŠ9½[n¥¥ ª‡ èó;öTSõ1ø Îèòv±ä SÌ j~û r¬­ > 5»^ ïûjÔÜkéÑÇøúaäÞBk±‡Æ·2ߪ®¥ k‡ _ß!µ yTÅXyW JM¥
+rRë;6Ï,!õpý8éíí`%÷æsÝf6jé¡¶â}ë×Áv û’{ò,ôæ{Yt —Ø]/ ¯×!°þî.õÔ+ì¿ q/Ô Fw¹¤â{‡“}p|'Ÿ
+²è¹m C
+o˜LÍ¥$ù-l›H áÅ ƒ‹Ûš \`W
+‹:åõ¤^«´_?ÎÑÛ^­ ?·ù:¸Þud[ò¦`«´ Ýýµfÿ0ƒK!ÀLg#SŠöŠv mOYÊ/rM°Z
+²Øè Žì´c ü· µ×îƒ Lù µ•˜J͹{ã<å jÉÈõõƒÑé
+c)!4—³Ñ{È Åí5¾D-’hîe 4 Ó¼sy%Ún„X’s¥ØÂö±
+Ê|90Ý똶½sª éÆÒ®ƒéþvÁe¾ÅöÙ§·%÷wê t.ôr
+âêoxÈ1¢aþµËz!êÓž f6 lºŽÁî]Ñ¡š0»°MlÔÐsð]›³± ê'ßß- ‡ Xõ¶h£æ\‚wÝ v•דø ¬·±ë>íÓ>·ø:˜^ ä\òS½®U\»êþR¯‡êà ̥î±%órf
+)ô–³"Op 'Ì+¦ 6:£ÛÛ#Gì;û|ÛehÑùT_¢ ‡žÔÖk» :EÞöÌÏh6¨iå>¥p»„Ücv5¿D r %ò
+Û›
L¤Z7êí‹Ø‚X«<Æ1Ú<Y• íuÌl^0£Í©^ ÛæAK+¨Z²Oo‹–ÿm-ù {» ™ï.=µÞãë ÷BýaÛás–Ÿ÷ÙŸ£‘ '¬ð ß·™ ê’ƒë‚ò\ßð ¤–ð
+ ·E ‘]ƒ«À
+mòº ê!í þÜ«ë˜xÛç'ÛßiɶèMÇ6 -ú»ŠûÚ¨· °a «#>ö¡á%Ëž°™d Àv' ½Ëm£›²à^ð²Éõa žhëð¼ÝԌЃ
+²² Õb#RÃB¿•´ ”,wçÛ%zÃ%gÜH
+*Þ{Vl/~ˆ-KPÚì~Rë 5@¥ñöéúñ
+
+dž‡mbÛm
+¶o@¡
+6¶/Q»` þË—i Ï5ã„qF(hh§´PÑNÜ
+K§¬ŸTû2ûåp¸ ÜUÏÑìuñ„ýRf`yN Ð
+ ¶›¨ôú†éüFE𬾖z
+KfãØ”šÐâSZ ñKÔ¦¡ }Û¨çįc“Ÿl_ߨȶæMÁžòº6Ýýµf íï¸ÉVYe 7´QäI É¡ü 0A+0
+湓E,˜’Ã. Ûâ
+L€x`½CõˆI
+(% ^YRÉ> &­LtHÍûbÌ +‹¬½±="¢A¥¤6|lyƒîpF Gø:¨„c
QœÉØ oèȺ 4C<æ °‘.×PÂÆ´ùP‡d‹ò€bL?—l*˜ ‰Ðß a öAä€Xìì ô“ȇ;&åQ @oè; ¢Cî8P<ãµNÚ+Á*&E³8ðÔÂ0d ˜ ïÚ·Õ^
+í))öÞ\M›˜NÚSÄ+ùÚögŸô¹µ ëZ\ËZ_›NíRZÔq‘ðµ ¿€>3±ñ8Ž©Ï|
-6p@»‘~ máTªßè ‹‰KäYѹáÎù'`Œ4/ (&Bámršvž$K€ SM¤ Uã z
+™@Ï
+
+ë¼m`=;Ū
+Fš›{ -

+ :àg JŸ \ œ£ÙÈ(ˆˆHG ñ5±y>
+£Ãe`!'Û(P²½dû&ÖÿZôP>¯Ðí
+H Wš <á£×!î'õš`?·œPŒt vØ ÒC nD’eb÷Vâ]´5ƒ­•m nà \—™Û?
+U !¶àÚ èS` õuŠ{ ½nÖ>óºÏO¶¿S’mÑ›Š­òZ´w öµQ¿Ð¾s1(ëŽCÿù8Á%
+˜ýnñD“ €ˆe Ý¢7 JøãÌ'H ¨µU‹6U¥ ¾>-7xxÅÕä ã b$
+#.–!—Ò}%G¬> n@wcs­ça = ø²™I|Qm¿Hùp.Dð0 É2 ƒ£ '‚+_ÇÌ e 3[õþ:Ø ¶ÁUE\á€$Û¢
+ :z†ž¶ë JJÞç€ q ýEÜ u` ¼“ ’›~ý98 Ÿ äÏLÛÄFÅý góÏO¶
+þEmN/ ¼mÉF#5ò> Âã"­'õ;Yo£· Zç}nòu0½ªÈ¹äMÁVi-ºûkÍþòþ¹ lµR EL m užˆž ¥<;]7ºy ¶¹
וO
+’±æOA¥ ðÈ-î°F”j*W
+ MàÄ͆` | ¿È 1d¤Á§<"Â^ÃëS7ó~T56ꬺÁD±ªÆNŸ5»‚ϪÛ̯O½ |Ÿûup=Š
+Ê–BœÎ Yó,5Fö ^‡¼f™ \ÒÂë öBýa¥ ¼¦ð½så

+¨t'°¤mæ Rå¿Ù_ß°-/KZˆ
+¥²-Ú¨$ž ‚˜òˆ‡‹ÀžÔMÜóÛËèm³¶™· ~°½éÈu¬xÓ¯MZ‹î®²¾6êDú8AŒ0xþ3>€7Áâ²
+k¿ Z)« áÕYçy V¹ÉAj¯ÇçÁ `ÅD|
+° X¨
+gĬˆR! ž'dÎ`Gű4€>| ICâ[¢*þeù¼!0ÖL
+Ï) O/T€e ( k ô ºÅJBm­ç̤| Ó!)×7¶G–ëTDæ¯R¢eͦ€‘ï’Ù + i¡ p¬Ý‰á ô“8
9É›€}š%ž \-x OàˆkŸ á ªÐ‚>‹¶+Ç( ‘*±éÝo˽zVQ É#9Y$u Ÿb^É×¶Gû¬Ïí=8^TãZ ûÚÔj Óª O _ ñ“Ù:„ ^¬³ø
¶l*3UA}ÈUÙŠò޾“¥ @æêñHidåxPåü’´¨- ’Rèî®Xù& Á& Ì6FO‚ž‡×DB¬+)å è¨â! >|
=8 '€¼_ çC.çAp½ÍÄv¡ãº NV¹1 óâöp'Í¡Feãz:Mç 4ïÌökÉÓá’I9Ä’ i q;ê æñí ô“8RÛ„3$«s³œú
³Ëär8îÈ+×>«’NÜ.:2­ìɱRP †k~Ö°¾V+Õ"÷+¤Ð9
+‚Ú‰«”WòµmÑ>ë×Þ
+ì®jq-K}m:µ iQÇEÀ×F|ÔñÁF˜–{`—¢²Q™uü 9gX }Ôñ³Êµ úO
+ŸT làG
+ „ «r¯OÜ «9ßuüΫ ˜øu´ uò9
+•±à ²Pß ÝäªOnÔÏ™¢c¦Y¶ÛF ` B•Œ×™¯;Ð Õ<ÓÉ÷€ Ê Ln몯 c ™ì”ØÀ' ¿ GÝy‘÷“zͺ
+ š¡±†s4"T>M¾ù n> g•‘ šÓj¹¾a o'˜Ë&úO
+ÿkÑ@:_‰zq”¼7 =©¯oĽ Þ6k›yÛè'ß›š\?ŽEo:¶ÉkÑßUÚ×Fýªã{PlB[Ê¬Ý ÕVT#M Wi y¨ Ý,@g
+Ä”–‡Ž Zå ÉÈLS06 A奱4Ä tÊ ¦ °,„T•©˜`ÈSH{|+£ÚÎת²ñ!6y 2& îF
+ <x€]H÷!Ást}w«é³‚a]_3 Š RÛî oT‰xÛ•Råi _«
+ ¨"D÷:|
<$†ç&â ”½ ÕåEÞOê´€ 0pª=•s48¡êü è3L`™YÝ Xµù߃é & hU Ý?—L É,ʆÒ8ª]Äõ¤¾¾ ö6zÛªmæm›?L §!Ûz7ýÚdµèî*ék£ íW›C&
+!þ ÊPSs >%Ýí;ž4Ãò–¼ÓEå¯UÇÈ– ò2f–‚
+}«Ï
+-kJÒgÝ&+i©VU µ6byÈ.Œj€ ¢r€
+²¯ÄÝÎΔ2 QÕnÇõ;‘­(€ Oøö¯ +yø±è¼D ê9mS £ë¬TÖ»³Œ ýSÆ—
+˜ç‚‡ÿEÀjWP½o Š‹óÁåù6úInA_ m4ª0m aÕéÙ—±QGAµ$U
+¯c^õM
+=‡Yðùâún¯)]m/µŽc¹eÍA Bv8ÑÐ"®•¸ŠúÚÉÛ6=§Ývxcú:´ã¹àסY›°žZùK þÒùB&ÝKêýΉí Î gÓZ" Âþ‹ßèÖ¡
+vy% ýnZ‹!“{È@½’
+â5"ÉwÓZQ RÇË ë ƒJ"ßÊlùࣙ e aÐ]p
+€lðwך ÄØ ÒF ˜ ‚XZŸš¿Œ xÅ —jIÔ2óÄ<xÍ ª'ß (H‹£çc]õÄ<¤@Õ|
JL¨%–R¬^±‹ûIüa» ±Ž
+ã14
+Å©­%ô»eí1k %ð ÷ ›×7<‡7ée÷† Ž @
+Ë :cÚ„u
+ÔCÔ }Û¨ÇÄ×±ÇO®
+ÙÖ|
+úµJkQÝ_+ö ë.f–мúåÒ ÀªÖoE‡YÌT÷"ßñy£ b&Ë$Ω‹b‚1
+<To5Cð]0Dù©SE Y[IÜjФå†Hó]ÍL¸‡ Û¨Gê<¯Žó$C ¤<ÎŽ?Vš¡O@ UoT [É ]IéqÓ~›õ†½ªµ
N®<ß  ¤¨w%ó¹`k ©ª¨ ¿ ën¸Ìì|
Îåuˆz¡Žc¬Ž ³jE:G{Ajo88œ3;Á"' Ü>ÍF“ïk–2ÁØ<k! «vÂFN õÐ7‰] u ÷9zݪçÄç&ol *²-ú¡_×*¯]u ­ØŸZ&a“Ä¥»>
+{j`­¢8jµ
+ ñâ$ËNV¡ƒ 6AÌÓ.}’3Qˆ¶ ~/L¬óë±0`))~±SdÕX
+é‘ ±/Ó' ¿ ðƨÀ`ÒDíèý¬î Iܧ“¨²ƒWŪÙÙßAoÖ
+ S
+ÛÄ³Ü Ø
+60ml õG‹H̺
+Y®‹
+J¨óü¦>ÄC^ªÐ0'î&”CÖOâ¨î J­»+ä Ü•B«]ÂÅ;Ø<f ¾# KµÏ–‡
+eUaªÉ#•¼­Wå
+¼@iv¢µ‹j'®r^É׺Gû¤Ëîî ¯ªq-‹}mzµ‹iQÉEÄ×FüÂ:U=£hGúØLêÖG:±NR?n­þSϼé£A ª¢[ú˜cL$}ÖPΪ s]¹Í§ OGp± ‹ì: Ä£¥ìîz¦ qwm6è«WŒ\¼¤Û‰ðeù¸ z—wŠNøb›Pg =Ú É¯¬I|
™ø.ï¨ b>Ù6×Y Í{¿ ô?‹žPG B< fN %`õ:Äý¤^³A_
++–wŸ£Õ3¡–ßPSy­3 ^w ^ ø§¬¹ð
+êP© „ø.l~Vm£ù²U
+Ã7 Û¨«¼ÏÑÛnm3¯ ýdûÚµä\ô¦cO ]›þþZ»Ÿ§·A½?£–1j@êA
+ŸÃ[2tçÕu·’Ç9¦ºXH g= “ס´ ô–
+â>ÚGÿ•÷÷Ú?§·NíX=õÏé-:›¬)C†^”måô )! ?‘Oªm A”•ÞˆçI
+Õ: Ä]Ù&þTúHÅšÅà'ÛŸ:!¨’ ð9¼½ ýº«Œ¸Ð:û~¾äõ¹c¢¾çr (>„½P'ä!|
«NžÛ9ZG™žñ`ßrÎ vpM5W_>ú?ù¾! bô:åhçª P¸ èç –/‰] u ÷9xÛ«çÄç>ol Zò\ô©cO
+êù Õ
+p_ Ž™$€È“? RB,Øç@<˜
+a—Ô®ïd VDæ œÃ‡3Ý* '¬ÊÎcòþK÷É k¹ñNP« @°~|
¿ fÈ  ²ðÕªêFýÒ} µí qì òí³—òI¿+Õ ¤N—Nމ‡ ¨›5|öé ÊÖìÐõc[òG Y^Îþ –)¯êÖ>Y0þ’ôµ
+ï°Q ÉÞxý9¶¾ rõªê•mVá Ö™ø×ÚÃÆò€%U îÑμ­Wç¨QÇ­¨ß!ª
+xÊy'?öèÚ'}îîkgxS e±«VíBZÔñ—ªüðõQ q½Þ¹k™m*·¯ e‘n$¿ÓÇí%Ò/v%}rÛ
pLX ^SH+á4îä6“ô¨eo¶iš®'ÄzC@>×{và ;ev!}î9 Õ'^WâÀ:ê¥m-¸Ñ•²Ž fm ¼­ ¶–iµýjWT#Õu0-Ý õÐcIÓÕ/K–â Q’ž]‡¸¤³ªŒF5úî²^ˆÃ­© «îöOrû Œ• Ô
+ ú±³{âqwI OfÜ6¶§§Ç ³êŽŸäö^ôpÖ^g­)ßÉíG`×A=¤½ÑŸ[u
+3o»¼ñ}èȶêMÞ Ûµw ÷µ ‡öÿóë—·x½] vüó/Ï;µê* ‰bªÖÓUÑ–øúùjŽÀCjªöh¯{7^gÕ< oR›t ¿Þ
+
+\¿Û Ça
+ÿùn`A@+™¸ <Â
+ Õ³ © ù ÏI Ctå
+c‰$Q ºœ´ ¨{h90»š›D Êe_1
+o2Ì

+ ‰Ï»ðê$ƒ˜IWª(‚𹕠$”ÀgµHê0è§ZSŠUã² ³
+u1‰ :Ä &`¾Ø¬ÁK—¤ñZ@Ìáë” èöDíƒÐú<ÕÔq'©
+êz?寰ÉQ§E ^
+¸±
+¨_¨œ®ËL 8¦çý­*Ê à>%ôØ ° /
àO $héyˆóˆ¤â Aey ré÷Y Ѭ©tôú9B¯ )³ 5N:X¹^cÂ[Ff2 :7f«|
7JÔuh¤¨ŽÏ’Jó ‡)BB j8–2Å ›Ó‰– dIÚ(
+W±­!¨Lªçjƒ Ü
+À†¨R- T
+ª[¾Àf u¸hrô:ªìª²Z1Bw ¢
+
+P¼ S yŠnd[MÕÙ<| Ãl¯`MØÊŠ . ‹’Iãa ®Þª »
+Î3É 5æh*ït/ — l뽌^
+M„j‰ÌBW7Öð¯A¡ª&5»gÝ'MúT`ï Mš7Ç×ß ³ š°(
+H–®g¿¿ Ö[
+Ä/":® ^>›aÆ ÇUIåRº5döç1£bw ’µö‘ «}Å(º~‹e‡êuÒ ðb€|ñcê®ÛNXP× Œn
+ WÒëhb÷8ÂfMas
+&¶â¶ní ·²2ÕÎV íƒ×¥Ó e,XBSž!Š Í ’0Ô€
+‹šÝ  ~ éVÒéSÒ¥râÓOëû-æ+Ç•S°®· 4 = n^œÓ- AˆAQó{
+E4Ö’ÔElZ/Êl„U­SG ÑÛs^
+u ´A70ÕYÙ&EÊ|W X€ ߌ¢WgãlÐ B»P6)Xæ°­Ž jøž e¶Ã ’
q)6D× Ò„4^WË‚ÌfPz´# ¬O¥€ªCkIÆ;Uw†ïRûf«ÎŒ
+UDidôI±?5‡¿3G LëUu «¯*Ú©2'
+
+êTÿ Ò¤¾ o^ ¬ü®fÂÞnŒ©áT'S¢ð $#ãg
+U KµçÍâÔ ÓÃ0
+LÔ .
+†‚¦¢€ ?¬6ïl=WH OÞt
+ gŽXÝØÅf1G€ÐLG{Ð
+ݼ E½†‘„ 48Ëj ƒ ½ŽHš"KWŸbB5ŒµXÞÊ«ø¼nÔ™ÝáÃÕÝ&]PP6» Š ‚sþ Ï¥ó û‚ÙC0!;µ}ሆnÉ
ëP
+¡;Rcõ1 - =~«½1Tir× Óœª ô€¥h6¢dŠú¡‚l 4¸Ì êÀˆ  ûŸ [ ó¤©Aw_Ñ™, °1º )­‹Ö´¨C
+o†ªði.EV§ ñØVOȉ¸- )æ¸1 ] Õ ëO³v² d¾^ýcìZ6‡`'[ˆ ‹À›(¹ì:N2J|
»y#OÝ­ ˆbR Ð:à ò®¨«8“€~ ë 1é^c*c ÀÔü uR$]€w馴äç™ F¤{–ŠÌvð:Ò Rŧچ¢Š  ›6¿®DÊ[Åh tz8 C cMý×&šªÞ¸Ùñ¯ãr
+µÁ J5œ
+¼( ²*“ ½Ïº°˜t+"Á4`o ѯ
+ ƒtJ„T
+1 éœ ûÁY •°Y ‘̺ œ•¨: ˜ÅÆDpD ?O!¸G & EÇà’€]EÌ„‡ ¬ÐjøH“ Í«*­Öïš µ ú7a m‚1´ÎsìPŒ™‘ Hñ`ÈIŸÂ§ëŠ‘‚
Ìê@WÀø§Åò¦â J¬ -h:K ¢ KCuØG"_з QU
+êÝ1sŒú®SÚK¼,Ã
+“ ‡ ½
+œ¨º¹E´¤Ö0ÝÓ’ŸV»¶ŽEåj¡è Zd Qh lÞ 2Å(˜C 8TGÖh¶ Á+IéË ¢, ¡å&ÅNRl럱»ÏˆT uPtÏa"Q¯
+„p Ʒй0 hV‹eÐ%G "U—m ‹ª¹¸[ßš(êÕ¼Á(f ðÓYÐO»ú ú FuÏVç Æ€ŽÚæ
+\bw$ÏHÁ¦‘faô ½]{ Á÷IÑåü H«NEõƒ'“ò9Î&C ʽ —’‹t×}ÙtÅ
+ 8"´úÁ¤jàSϤQ„
+Ê0GÌ ? þ±Õ˜ ß Ty¿Ê ÞÆ$
+’‰Jñ9Äíd¶eõL Æ
+ g™ž~€dRz¿Q©àš+ _')}›¨ A ·TÛ Óé‰J +]Õ ³m`ÛÛ¬1[ –B€ñ
+1¤<Q©P˜´XqóÂX
+¤ *U”À}9‹›Iv '*Õ­j Ù|+~^%;Á0
+j±ùI›#ÉD•M&*EÙ¥e †a º 0Pi¶ <šÉYjTU3 • UÕ-†©RR ŒÁRD”TÒMqh
+ ieÀÒ
ܨœË$ƒ {'ô«1pÆÇl „E p*Þ˜Af Ž2q©œITí¿Ù HÉV&.m ô¨d0®QpÏÕp)PN ¨ ¢‰* X»‰K›úñ”/ÃŽ ê9‡PÕ0á}Ò• 9ä[Êõ/¤¹ú=*ò›ãç®ôoU¿uÅ[Ÿß·ú}üÔUÒO]ñÜÙ jýõú‡ß^ ÿO
+ ÿúí?®‚ô•ÊêˆM?«¢RÊoÿvý ûÛ×oÿýúÇß.›íòv½_ñ•ÿÿ̺?½9ØžßÜ
+ əϦª@ùhoKQ µ¼²Æö =é@¬«¾2XÛŸÞ¬mÏoÖŽÇ¿d
+Ô„Í ë’ÖÛOÁùMrhôÛ ¬e盽ýéÍÞöüfïxüKö Gñ°  mo $ç7ÑÉ•ÇώܼíOoÞ¶ç7oÇã_ò–tï”P
+Ô>ZVÑ
+Mt²Ï{Kp ÷/»mOoö¶ç7{Çã_³ `%š’¦T{{ao“ÞÃú¦ìŒ ¯ ž“7IŸ_¡û£)³¾ už
+ôc0ÃúÞî˜K ‡?²?i̺=ûšÿxypòÍû ÄSW‡ôøé ÝGUõ;MÞÂÉ n 7ÿLÞÖg Þö—'oçû Ä›v„ ך³ÚÐx}p– Δ0 ·Æ ?8Ûž}qv¼<8ûæý?âLH: ´ŒjUŽª>OÞÊÉ›”-Í?yò¶>{ð¶¿<y;ßÿC-‹R/ ,Q•pZu òÖ Þ>·8íÏàm{öÅÛñòàí›÷¿çÍ+1¶ Dæåô«uú!€6|
Ö—)„ןŸÁmùUÇÓòVâ÷¿ ¹ ¾~ ’Ç×ÿ
+hY
+endstream
+endobj
+11 0 obj
+7175
+endobj
+16 0 obj
+<< /Filter /FlateDecode /Length 317 >>
+stream
+xœ5RKrC1 Û¿Sp Θ¿}žt²jî¿­„'+°-@B./YÒK~Ô%Û¥ÃäW ÷%±B> íšÌRÅ÷ ³ Ï-¯GÏ ·-
+ Q =ø2' "ÔÏÔè:xa—> ¯ N) x “ ¯á_x”NƒÀ; 2Þ “‘ $ÁšK‹MH”=Iü+åõ¤•4t~&+sù{r© j£É
X¹Ø ¤+)
+$ =‰H²r½7VˆÞ W’Çg%& Ý&±M´ÀãÜ•´„™˜B æX€Õt³ºú
+LXã°„ñ*a ÕƒMž5©„f´ŽcdÃx÷ÂL‰
+†Ã P›}• ª— ÓÜ #¦GMví²[6ï!D£ù3,”ÁÇ($ ‡Nc$
+Ò°€ 9½°Š½æ 9 Àˆe š, mh%»zŽ
+ÀМ³¥aÆ×ž×óþ E[{£
+endstream
+endobj
+17 0 obj
+<< /Filter /FlateDecode /Length 49 >>
+stream
+xœ36´P0P040 ’F†@–‘‰BŠ! H ÄÌå‚ æ€Y @ ¢8 ®&‡+
+ Æè
+&
+endstream
+endobj
+18 0 obj
+<< /Filter /FlateDecode /Length 248 >>
+stream
+xœ-Q9’ A Ëç zBsÓï±Ë‘÷ÿé
+Ê ƒ†C :-qPÆO –+ÞòÈU´áï™ ÁwÁ¡ßÊu 9 HÒ TM¨]¼
+½ v
+f ó¤5,ƒ ë ?c
+7zqxLÆÙíu 5 {×kOfP2+ qÉÄ SuØÈ™ÃO¦Œ í\Ï
+ȹ Öe ¤›•ÆŒ„#M!RH¡ê&©3A £«Q£
+Å~éË# aU#j û\KÛ×s Î 4; «<9¥GWœËÉÅ + ý¼ÍÀET «< p¿ÛCýœìä7ÞÒ¹³Åôø^s²¼0 Xñæµ Mµø7/âø=ãëùü ¨¥[
+endstream
+endobj
+19 0 obj
+<< /Filter /FlateDecode /Length 90 >>
+stream
+xœM A À
ï¼"OPDÐÿtzÒÿ_«Ô ½ÀN ‰ E‚ô5jK0î¸2 kP)˜”—ÀU0\ Úî¢Êþ2IL †Ó{· ƒ²ñqƒÒIûöqz «ýz Ý Ò
+"X
+endstream
+endobj
+20 0 obj
+<< /Filter /FlateDecode /Length 210 >>
+stream
+xœ5PË
+C1 »g
+ ¨ džV½uÿkmÐ;a ÿBXÈ” y©ÉÎ)éK>:L ¶.¿±" ­u%ìÊš
ž+ï¡™²±ÑØâ`p &^€ 7`èi 5tႦ.•B Å%ð™|u{è¾O xj rv CÉ`
jº MX´<Ÿ N âÿ~Ãî-ä¡’óÊž ù œíð;³ná'jv"Ñr 2Ô³4Ç E
+<yE¦pâ³ÖwÕ4 Ôf N– ®N?Œ `"^Y€ì®D9KÒŽ¥Ÿo¼Ç÷ @ S´
+endstream
+endobj
+21 0 obj
+<< /Filter /FlateDecode /Length 247 >>
+stream
+xœMQ»mD1 ëß \à ëkyž R]öoCÉ Â ¡/)§% öÆK á [ ¾ä‘UC
+?1ì3,=ÉäÔ?æ¹ÉT ¾ ª›˜P báýh ¼ t/"+Ê ß e sÎ÷࣠—`&4`¬oI& Õ¼3d‰¡ŽÃA›T wM ,® Í3ÈíV7²:³
lx% âÆ D Ù Í`£Œ±• År

+’ Z`×é Q‹‚+”Ö t¢ÖĺÌà«çöv7C/ò਺x} ëK°Âè¥{,|
®B ÌôL;wI#½ð¦ f R™ ‘•:=b}·@ÿŸe+øûÉÏóý (\*
+endstream
+endobj
+22 0 obj
+<< /Filter /FlateDecode /Length 392 >>
+stream
+xœ=RKn 1 ÛÏ)¸@¥ðMrž©ÞîÝ [›ÌTª
+/ ¶1”— ©%?ê’ˆ3L~õr]âQò½ljgæ!î.6¦øXr_º†ØrÑšb±O
+É/È´TX¡VÝ£Cñ
+( -à á¾
+ÿñ ¨Á×°
+rÃ{d `JÔn@ÆCÑ HYA aû‘ è¤P¯láï( WÔ¬
+¡tbˆ
+– )¾«
+‰˜¨Ù ‡„•’ª
+ÒñŒ¤ð[Á]‰aP[[Û xfÐ ÙÞ‘ 3íÑ qY k?=é£Q2µQ Mg|
ñÝ2RóÑ è¤ÒÈÝÊCgÏB'`$æI˜çp#ážÛA 1ôq¯–Ol÷˜)V‘ð ;Ê ½ýÞ’ Ï{à,Œ\ÛìL'ðÑi§
+ ­¾
+býƒ?lK›\Ç+‡E ¨¼( ~×A q|XÅ÷d£Dw´ Ö# Õh% ÂÎí0òxÆyÙÞ ´æôDh£D
+ÔŽ =(²Ååœ °§ü¬Í±
+ž &{o´ ”Į̀„ Ôvz¨¶Ïc
+Ôwžûúü . ¡
+endstream
+endobj
+23 0 obj
+<< /Filter /FlateDecode /Length 80 >>
+stream
+xœEŒ»
+À0 D{¦` ~&fŸ(•³ JÜpOº{¸: 2SÞa†‡ ž ,†Sñ ™£`5¸FR 죰n_u æzS«õ÷ *Ovvq=ÍË ô
+endstream
+endobj
+14 0 obj
+<< /FontDescriptor 13 0 R /Name /DejaVuSans
+/FontMatrix [ 0.001 0 0 0.001 0 0 ] /BaseFont /DejaVuSans /Widths 12 0 R
+/Subtype /Type3 /CharProcs 15 0 R /Type /Font /FirstChar 0
+/FontBBox [ -1021 -416 1681 1167 ]
+/Encoding <<
+/Differences [ 46 /period 48 /zero /one /two 52 /four /five /six 56 /eight
]
+/Type /Encoding >>
+/LastChar 255 >>
+endobj
+13 0 obj
+<< /Descent -236 /FontBBox [ -1021 -416 1681 1167 ] /StemV 0 /Flags 32
+/XHeight 0 /Type /FontDescriptor /FontName /DejaVuSans /MaxWidth 1342
+/CapHeight 0 /ItalicAngle 0 /Ascent 929 >>
+endobj
+12 0 obj
+[ 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600
+600 600 600 600 600 600 600 600 600 600 600 600 600 600 318 401 460 838 636
+950 780 275 390 390 500 838 318 361 318 337 636 636 636 636 636 636 636 636
+636 636 337 337 838 838 838 531 1000 684 686 698 770 632 575 775 752 295
+295 656 557 863 748 787 603 787 695 635 611 732 684 989 685 611 685 390 337
+390 838 500 500 613 635 550 635 615 352 635 634 278 278 579 278 974 634 612
+635 635 411 521 392 634 592 818 592 592 525 636 337 636 838 600 636 600 318
+352 518 1000 500 500 500 1342 635 400 1070 600 685 600 600 318 318 518 518
+590 500 1000 500 1000 521 400 1023 600 525 611 318 401 636 636 636 636 337
+500 500 1000 471 612 838 361 1000 500 500 838 401 401 500 636 636 318 500
+401 471 612 969 969 969 531 684 684 684 684 684 684 974 698 632 632 632 632
+295 295 295 295 775 748 787 787 787 787 787 838 787 732 732 732 732 611 605
+630 613 613 613 613 613 613 982 550 615 615 615 615 278 278 278 278 612 634
+612 612 612 612 612 838 612 634 634 634 634 592 635 592 ]
+endobj
+15 0 obj
+<< /six 16 0 R /period 17 0 R /two 18 0 R /four 19 0 R /zero 20 0 R
+/five 21 0 R /eight 22 0 R /one 23 0 R >>
+endobj
+3 0 obj
+<< /F1 14 0 R >>
+endobj
+4 0 obj
+<< >>
+endobj
+5 0 obj
+<< >>
+endobj
+6 0 obj
+<< >>
+endobj
+7 0 obj
+<< >>
+endobj
+2 0 obj
+<< /Count 1 /Kids [ 10 0 R ] /Type /Pages >>
+endobj
+24 0 obj
+<< /CreationDate (D:20120208010242-05'00')
+/Producer (matplotlib pdf backend r8292)
+/Creator (matplotlib 1.0.1, http://matplotlib.sf.net) >>
+endobj
+xref
+0 25
+0000000000 65535 f
+0000000016 00000 n
+0000011648 00000 n
+0000011532 00000 n
+0000011564 00000 n
+0000011585 00000 n
+0000011606 00000 n
+0000011627 00000 n
+0000000065 00000 n
+0000000315 00000 n
+0000000208 00000 n
+0000007565 00000 n
+0000010353 00000 n
+0000010153 00000 n
+0000009800 00000 n
+0000011406 00000 n
+0000007586 00000 n
+0000007976 00000 n
+0000008097 00000 n
+0000008418 00000 n
+0000008580 00000 n
+0000008863 00000 n
+0000009183 00000 n
+0000009648 00000 n
+0000011708 00000 n
+trailer
+<< /Info 24 0 R /Root 1 0 R /Size 25 >>
+startxref
+11865
+%%EOF
=======================================
--- /dev/null
+++ /trunk/examples/parallel_evaluation_mp_example.py Wed Feb 8 17:16:16
2012
@@ -0,0 +1,41 @@
+from random import Random
+from time import time
+import ecspy
+import math
+
+def generate_rastrigin(random, args):
+ size = args.get('num_inputs', 10)
+ return [random.uniform(-5.12, 5.12) for i in xrange(size)]
+
+def evaluate_rastrigin(candidates, args):
+ fitness = []
+ for cs in candidates:
+ fit = 10 * len(cs) + sum([((x - 1)**2 - 10 * math.cos(2 * math.pi
* (x - 1))) for x in cs])
+ fitness.append(fit)
+ return fitness
+
+def main(prng=None):
+ if prng is None:
+ prng = Random()
+ prng.seed(time())
+
+ ea = ecspy.ec.ES(prng)
+ ea.observer = ecspy.observers.screen_observer
+ ea.terminator = ecspy.terminators.evaluation_termination
+ final_pop = ea.evolve(generator=generate_rastrigin,
+
evaluator=ecspy.evaluators.parallel_evaluation_mp,
+ mp_evaluator=evaluate_rastrigin,
+ mp_num_cpus=8,
+ pop_size=8,
+ bounder=ecspy.ec.Bounder(-5.12, 5.12),
+ maximize=False,
+ max_evaluations=256,
+ mutation_rate=0.2,
+ use_one_fifth_rule=True,
+ num_inputs=3)
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, "Rastrigin", str(best)))
+ return ea
+
+if __name__ == '__main__':
+ main()
=======================================
--- /dev/null
+++ /trunk/examples/parallel_evaluation_pp_example.py Wed Feb 8 17:16:16
2012
@@ -0,0 +1,47 @@
+from random import Random
+from time import time
+import ecspy
+import math
+
+# Define an additional "necessary" function for the evaluator
+# to see how it must be handled when using pp.
+def my_squaring_function(x):
+ return x**2
+
+def generate_rastrigin(random, args):
+ size = args.get('num_inputs', 10)
+ return [random.uniform(-5.12, 5.12) for i in xrange(size)]
+
+def evaluate_rastrigin(candidates, args):
+ fitness = []
+ for cs in candidates:
+ fit = 10 * len(cs) + sum([(my_squaring_function(x - 1) - 10 *
math.cos(2 * math.pi * (x - 1))) for x in cs])
+ fitness.append(fit)
+ return fitness
+
+def main(prng=None):
+ if prng is None:
+ prng = Random()
+ prng.seed(time())
+
+ ea = ecspy.ec.ES(prng)
+ ea.observer = ecspy.observers.screen_observer
+ ea.terminator = ecspy.terminators.evaluation_termination
+ final_pop = ea.evolve(generator=generate_rastrigin,
+
evaluator=ecspy.evaluators.parallel_evaluation_pp,
+ pp_evaluator=evaluate_rastrigin,
+ pp_dependencies=(my_squaring_function,),
+ pp_modules=("math",),
+ pop_size=8,
+ bounder=ecspy.ec.Bounder(-5.12, 5.12),
+ maximize=False,
+ max_evaluations=256,
+ mutation_rate=0.2,
+ use_one_fifth_rule=True,
+ num_inputs=3)
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, "Rastrigin", str(best)))
+ return ea
+
+if __name__ == '__main__':
+ main()
=======================================
--- /dev/null
+++ /trunk/tests/test_migrator.py Wed Feb 8 17:16:16 2012
@@ -0,0 +1,40 @@
+import ecspy
+import random
+import multiprocessing
+
+def test_process(random, population, migrator, output_queue):
+ for i in range(9999):
+ population = migrator(random, population, {})
+ output_queue.put(population)
+
+
+if __name__ == '__main__':
+ rand = random.Random()
+ rand.seed(1234)
+ queue = multiprocessing.Queue()
+ migrator = ecspy.migrators.MultiprocessingMigrator()
+ populations =
[["red", "orange", "yellow", "green", "blue", "indigo", "violet"],
+ [1, 2, 3, 4, 5, 6, 7],
+
["bashful", "doc", "dopey", "grumpy", "happy", "sleepy", "sneezy"]]
+
+ jobs = []
+ for pop in populations:
+ p = multiprocessing.Process(target=test_process, args=(rand, pop,
migrator, queue))
+ p.start()
+ jobs.append(p)
+ for j in jobs:
+ j.join()
+
+ final_pops = []
+ while queue.qsize() > 0:
+ final_pops.append(set(queue.get()))
+ for p in final_pops:
+ a = p & set(populations[0])
+ b = p & set(populations[1])
+ c = p & set(populations[2])
+ print(a)
+ print(b)
+ print(c)
+ if len(a) > 0 and len(b) > 0 and len(c) > 0:
+ print("overlap among all pops")
+
=======================================
--- /trunk/docs/conf.py Sat Feb 4 21:42:21 2012
+++ /trunk/docs/conf.py Wed Feb 8 17:16:16 2012
@@ -22,7 +22,7 @@

# Add any Sphinx extension module names here, as strings. They can be
extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions =
['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.pngmath']
+extensions =
['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.mathjax']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -160,7 +160,7 @@
# Output file base name for HTML help builder.
htmlhelp_basename = 'ecspydoc'

-#jsmath_path = 'C:\\jsMath\\easy\\load.js'
+#jsmath_path = 'jsMath/easy/load.js'


# -- Options for LaTeX output
--------------------------------------------------
=======================================
--- /trunk/docs/examples.rst Wed Dec 2 21:50:04 2009
+++ /trunk/docs/examples.rst Wed Feb 8 17:16:16 2012
@@ -2,64 +2,194 @@
Examples
********

-Thhe following examples illustrate how to use the different, built-in,
evolutionary computations.
-
-=================
+We always find it easiest to learn a new library by adapting existing
examples to our
+purposes. For that reason, we provide many examples in this section in the
hope that
+they will prove useful to others using ECsPy.
+
+
+=======================================
+Off-the-shelf Evolutionary Computations
+=======================================
+
+The following examples illustrate how to use the different, built-in,
evolutionary computations.
+They are simple enough to be self-explanatory and are provided without
additional documentation.
+
+
+"""""""""""""""""
Genetic Algorithm
-=================
+"""""""""""""""""

.. literalinclude:: ../examples/ga_example.py


-==================
+""""""""""""""""""
Evolution Strategy
-==================
+""""""""""""""""""

.. literalinclude:: ../examples/es_example.py


-================================
+"""""""""""""""""""
+Simulated Annealing
+"""""""""""""""""""
+
+.. literalinclude:: ../examples/sa_example.py
+
+
+""""""""""""""""""""""""""""""""
Differential Evolution Algorithm
-================================
+""""""""""""""""""""""""""""""""

.. literalinclude:: ../examples/dea_example.py


-====================================
+""""""""""""""""""""""""""""""""""""
Estimation of Distribution Algorithm
-====================================
+""""""""""""""""""""""""""""""""""""

.. literalinclude:: ../examples/eda_example.py


-===============================
+"""""""""""""""""""""""""""""""
Custom Evolutionary Computation
-===============================
+"""""""""""""""""""""""""""""""

.. literalinclude:: ../examples/custom_ec_example.py


-===========================
+"""""""""""""""""""""""""""
Particle Swarm Optimization
-===========================
+"""""""""""""""""""""""""""

.. literalinclude:: ../examples/pso_example.py


-================================================
+""""""""""""""""""""""""""""""""""""""""""""""""
Nondominated Sorting Genetic Algorithm (NSGA-II)
-================================================
+""""""""""""""""""""""""""""""""""""""""""""""""

.. literalinclude:: ../examples/nsga_example.py


-=========================================
+"""""""""""""""""""""""""""""""""""""""""
Pareto Archived Evolution Strategy (PAES)
-=========================================
+"""""""""""""""""""""""""""""""""""""""""

.. literalinclude:: ../examples/paes_example.py


+===================
+ECsPy Customization
+===================
+
+The true benefit of the ECsPy library is that it allows the programmer to
customize
+almost every aspect of the evolutionary computation. This is accomplished
primarily
+through the use of function (or function-like) callbacks that can be
specified by
+the programmer.
+
+The observer, terminator, and variator callbacks may be lists or tuples of
functions, rather
+than just a single function. In each case, the functions are called
sequentially in the order
+listed. For the variator, the output from one call is used as the input
for the subsequent call.
+
+The following examples provide some ideas for customization that we have
found useful in practice.
+
+"""""""""""""""
+Custom Archiver
+"""""""""""""""
+
+The purpose of the archiver is to provide a mechanism for candidate
solutions to be
+maintained without necessarily remaining in the population. This is
important for
+most multiobjective evolutionary approaches, but it can also be useful for
single-objective
+problems, as well. In this example, we create an archiver that maintains
the *worst*
+individual found. (There is no reason we can imagine to actually do this.
It is just
+for illustration purposes.)
+
+.. literalinclude:: ../examples/custom_archiver_example.py
+
+
+"""""""""""""""
+Custom Migrator
+"""""""""""""""
+
+The purpose of the migrator is to provide a mechanism for candidate
solutions to be
+shared across populations (e.g., in an island-model evolutionary
computation). The following
+custom migrator is a callable class (because the migrator must behave like
a callback function)
+that allows solutions to migrate from one network machine to another. It
is assumed that
+the EC islands are running on the given IP:port combinations.
+
+.. literalinclude:: ../examples/custom_migrator_example.py
+
+
+"""""""""""""""
+Custom Observer
+"""""""""""""""
+
+Sometimes it is helpful to see certain aspects of the current population
as it evolves.
+The purpose of the "observer" functions is to provide a callback that
executes at the
+end of each generation so that the process can be monitored accordingly.
In this example,
+the only information desired at each generation is the current best
individual.
+
+.. literalinclude:: ../examples/custom_observer_example.py
+
+
+"""""""""""""""
+Custom Replacer
+"""""""""""""""
+
+The replacer callbacks are used to determine which of the parents,
offspring, and current population
+should survive into the next generation. And example of a
not-quite-standard replacer might be
+the ``crowding_replacement`` which provides a niching capability. An
example using this replacer is
+given below.
+
+.. literalinclude:: ../examples/niche_example.py
+
+
+"""""""""""""""
+Custom Selector
+"""""""""""""""
+
+
+
+"""""""""""""""""
+Custom Terminator
+"""""""""""""""""
+
+
+
+"""""""""""""""
+Custom Variator
+"""""""""""""""
+
+
+
+
+==============
+Advanced ECsPy
+==============
+
+The examples in this section deal with much less commonly used aspects of
+the library. Beware that these parts may not have received as much testing
+as the more core components exemplified above.
+
+"""""""""""""""""""""""""""""""""""
+Evaluating Individuals Concurrently
+"""""""""""""""""""""""""""""""""""
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



=======================================
--- /trunk/docs/moonshot.py Wed Nov 30 17:57:33 2011
+++ /trunk/docs/moonshot.py Wed Feb 8 17:16:16 2012
@@ -10,12 +10,7 @@
from matplotlib.patches import Circle
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import observers
-from ecspy import selectors
-from ecspy import replacers
-from ecspy import variators
+import ecspy
#end_imports

# All units are in SI unless stated otherwise.
@@ -158,7 +153,6 @@
plt.axis("equal")
plt.grid("on")
projdir = os.path.dirname(os.getcwd())
- print(projdir)
name = "%s/%s.pdf" % (projdir, str(fitness))
plt.savefig(name, format="pdf")
plt.clf()
@@ -200,30 +194,30 @@
constraints=((6e6, 10.0, 3e3, -10000.0, 4000),
(8e6, 40.0, 9e3, 10000.0, 6000))

-algorithm = ec.EvolutionaryComputation(rand)
-algorithm.terminator = terminators.evaluation_termination
-algorithm.observer = [observers.file_observer, custom_observer]
-algorithm.selector = selectors.tournament_selection
-algorithm.replacer = replacers.generational_replacement
-algorithm.variator = [variators.blend_crossover,
variators.gaussian_mutation]
+algorithm = ecspy.ec.EvolutionaryComputation(rand)
+algorithm.terminator = ecspy.terminators.evaluation_termination
+algorithm.observer = [ecspy.observers.file_observer, custom_observer]
+algorithm.selector = ecspy.selectors.tournament_selection
+algorithm.replacer = ecspy.replacers.generational_replacement
+algorithm.variator = [ecspy.variators.blend_crossover,
ecspy.variators.gaussian_mutation]
projdir = os.path.dirname(os.getcwd())

-stat_file_name = "%s/data/ec_statistics.csv" % projdir
-ind_file_name = "%s/data/ec_individuals.csv" % projdir
+stat_file_name = "%s/moonshot_ec_statistics.csv" % projdir
+ind_file_name = "%s/moonshot_ec_individuals.csv" % projdir
stat_file = open(stat_file_name, 'w')
ind_file = open(ind_file_name, 'w')
final_pop = algorithm.evolve(generator=satellite_generator,
- evaluator=moonshot_evaluator,
- pop_size=100,
- maximize=False,
- bounder=ec.Bounder(constraints[0], constraints[1]),
- num_selected=100,
- tourn_size=2,
- num_elites=1,
- mutation_rate=0.3,
- max_evaluations=200,
- statistics_file=stat_file,
- individuals_file=ind_file)
+ evaluator=moonshot_evaluator,
+ pop_size=100,
+ maximize=False,
+ bounder=ecspy.ec.Bounder(constraints[0],
constraints[1]),
+ num_selected=100,
+ tourn_size=2,
+ num_elites=1,
+ mutation_rate=0.3,
+ max_evaluations=600,
+ statistics_file=stat_file,
+ individuals_file=ind_file)

stat_file.close()
ind_file.close()
=======================================
--- /trunk/docs/polyarea.py Sun Aug 29 14:02:31 2010
+++ /trunk/docs/polyarea.py Wed Feb 8 17:16:16 2012
@@ -2,12 +2,7 @@
from random import Random
from time import time
from time import sleep
-from ecspy import ec
-from ecspy import observers
-from ecspy import replacers
-from ecspy import selectors
-from ecspy import terminators
-from ecspy import variators
+import ecspy
from Tkinter import *
import itertools
#end_imports
@@ -87,12 +82,12 @@
#start_main
rand = Random()
rand.seed(int(time()))
-my_ec = ec.EvolutionaryComputation(rand)
-my_ec.selector = ec.selectors.tournament_selection
-my_ec.variator = [ec.variators.uniform_crossover, mutate_polygon]
-my_ec.replacer = ec.replacers.steady_state_replacement
+my_ec = ecspy.ec.EvolutionaryComputation(rand)
+my_ec.selector = ecspy.selectors.tournament_selection
+my_ec.variator = [ecspy.variators.uniform_crossover, mutate_polygon]
+my_ec.replacer = ecspy.replacers.steady_state_replacement
my_ec.observer = polygon_observer
-my_ec.terminator = [terminators.evaluation_termination,
terminators.average_fitness_termination]
+my_ec.terminator = [ecspy.terminators.evaluation_termination,
ecspy.terminators.average_fitness_termination]
window = Tk()
window.title('Evolving Polygons')
can = Canvas(window, bg='white', height=400, width=400)
=======================================
--- /trunk/docs/tutorial.rst Sat Feb 4 21:42:21 2012
+++ /trunk/docs/tutorial.rst Wed Feb 8 17:16:16 2012
@@ -2,7 +2,60 @@
Tutorial
********

-This chapter presents three optimization examples to which ECsPy can be
applied. Each example presents a particular problem for which the chosen
evolutionary computation is well-suited.
+This chapter presents an overview of ECsPy along with three optimization
examples to which ECsPy can be applied. Each example presents a particular
problem for which the chosen evolutionary computation is well-suited.
+
+==============
+ECsPy Overview
+==============
+
+The ECsPy library grew out of insights from Ken de Jong's
book "Evolutionary Computation: A Unified Approach". The goal of the
library is to separate problem-specific computation from algorithm-specific
computation. Any evolutionary computation has at least two aspects that are
entirely problem-specific: what solutions to the problem look like and how
such solutions are evaluated. These components will certainly change from
problem to problem. For instance, a problem dealing with optimizing the
volume of a box might represent solutions as a three-element list of real
values for the length, width, and height, respectively. In contrast, a
problem dealing with genetic programming might represent solutions as a
tree structure. Similarly, the way such candidate solutions are evaluated
is entirely problem dependent.
+
+On the other hand, there are algorithm-specific components that may make
no (or only modest) assumptions about the type of solutions upon which they
operate. These components include the mechanism by which parents are
selected, the way offspring are generated, and the way individuals are
replaced in succeeding generations. For example, the ever-popular
tournament selection scheme makes no assumptions whatsoever about the type
of solutions it is selecting. The n-point crossover operator, on the other
hand, does make an assumption that the solutions will be linear lists that
can be "sliced up," but it makes no assumptions about the contents of such
lists. They could be lists of numbers, strings, other lists, or something
even more exotic.
+
+With that background, we can now explain that ECsPy treats every
evolutionary computation as being composed of the following parts:
+
+* Problem-specific components
+
+ * A generator that defines how solutions are created
+ * An evaluator that defines how fitness values are calculated for
solutions
+
+* Algorithm-specific evolutionary operators
+
+ * An observer that defines how the user can monitor the state of the
evolution
+ * A terminator that determines whether the evolution should end
+ * A selector that determines which individuals should become parents
+ * A variator that determines how offspring are created from existing
individuals
+ * A replacer that determines which individuals should survive into the
next generation
+ * A migrator that defines how solutions are transferred among differnt
populations
+ * An archiver that defines how existing solutions are stored outside of
the current population
+
+Each of these components is specified by a function (or function-like)
callback that the user can supply. The general flow of the ``evolve``
method in ECsPy is as follows, where user-supplied callback functions are
in ALLCAPS:
+
+::
+
+ Create the initial population using the specified candidate seeds and
the GENERATOR
+ Evaluate the initial population using the EVALUATOR
+ Set the number of evaluations to the size of the initial population
+ Set the number of generations to 0
+ Call the OBSERVER on the initial population
+ While the TERMINATOR is not true Loop
+ Choose parents via the SELECTOR
+ Initialize offspring to the parents
+ For each VARIATOR Loop
+ Set offspring to the output of the VARIATOR on the offspring
+ Evaluate offspring using the EVALUATOR
+ Update the number of evaluations
+ Replace individuals in the current population using the REPLACER
+ Migrate individuals in the current population using the MIGRATOR
+ Archive individuals in the current population using the ARCHIVER
+ Increment the number of generations
+ Call the OBSERVER on the current population
+
+The observer, terminator, and variator callbacks may be lists or tuples of
functions, rather
+than just a single function. In each case, the functions are called
sequentially in the order
+listed. Unlike the other two, however, the variator behaves like a
pipeline, where the output
+from one call is used as the input for the subsequent call.
+

======================
The Rastrigin Function
@@ -66,7 +119,7 @@
::

$ python rastrigin.py
- [0.9996479288978145, 1.0011106329445922, 0.9993723649808806] :
0.000347459890914
+ [1.000015980034728, 1.000420691084238, 0.9986289052268122] :
0.000408117434489

.. {{{end}}}

=======================================
--- /trunk/ecspy/contrib/approximate.py Thu Jul 1 06:23:41 2010
+++ /trunk/ecspy/contrib/approximate.py Wed Feb 8 17:16:16 2012
@@ -71,7 +71,7 @@
prng = random.Random()
prng.seed(time.time())
es = ec.ES(prng)
- #es.observer = observers.screen_observer
+ #es.observer = observers.stats_observer
es.terminator = terminators.evaluation_termination
final_pop = es.evolve(rastrigin_generator, rastrigin_evaluator,
pop_size=20, maximize=False,
max_evaluations=5000, lower_bound=-5.12,
upper_bound=5.12)
=======================================
--- /trunk/ecspy/contrib/micro.py Sat Jan 28 19:37:03 2012
+++ /trunk/ecspy/contrib/micro.py Wed Feb 8 17:16:16 2012
@@ -81,7 +81,7 @@
micro.replacer = replacers.steady_state_replacement
micro.variator = [variators.uniform_crossover,
variators.gaussian_mutation]
micro.archiver = archivers.best_archiver
- micro.observer = observers.screen_observer
+ micro.observer = observers.stats_observer
micro.terminator = terminators.evaluation_termination
final_pop = micro.evolve(rastrigin_generator, rastrigin_evaluator,
pop_size=10, maximize=False, bounder=ec.Bounder(-5.12, 5.12),
max_evaluations=3000, num_selected=2,
stdev=0.1)
=======================================
--- /trunk/ecspy/ec.py Tue Oct 4 07:31:53 2011
+++ /trunk/ecspy/ec.py Wed Feb 8 17:16:16 2012
@@ -112,7 +112,22 @@
"""Represents an individual in an evolutionary computation.

An individual is defined by its candidate solution and the
- fitness (or value) of that candidate solution.
+ fitness (or value) of that candidate solution. Individuals
+ can be compared with one another by using <, <=, >, and >=.
+ In all cases, such comparisons are made using the individuals'
+ fitness values. The ``maximize`` attribute is respected in all
+ cases, so it is better to think of, for example, < (less-than)
+ to really mean "worse than" and > (greater-than) to mean
+ "better than". For instance, if individuals a and b have fitness
+ values 2 and 4, respectively, and if ``maximize`` were ``True``,
+ then a < b would be true. If ``maximize`` were ``False``, then
+ a < b would be false (because a is "better than" b in terms of
+ the fitness evaluation, since we're minimizing).
+
+ Note that ``Individual`` objects are almost always created by
+ the EC, rather than the user. The ``evolve`` method of the
+ EC also has a ``maximize`` argument, whose value is passed
+ directly to all created individuals.

Public Attributes:

@@ -162,31 +177,17 @@
def __ge__(self, other):
return other < self or not self < other

- def __lshift__(self, other):
- return self < other
-
- def __rshift__(self, other):
- return other < self
-
- def __ilshift__(self, other):
- raise TypeError("unsupported operand type(s) for <<=: 'Individual'
and 'Individual'")
-
- def __irshift__(self, other):
- raise TypeError("unsupported operand type(s) for >>=: 'Individual'
and 'Individual'")
-
- def __eq__(self, other):
- return self.candidate == other.candidate
-
- def __ne__(self, other):
- return self.candidate != other.candidate
-

class EvolutionExit(Exception):
"""An exception that may be raised and caught to end the evolution.

This is an empty exception class that can be raised by the user
at any point in the code and caught outside of the ``evolve``
- method.
+ method. Be aware that ending the evolution in such a way will
+ almost certainly produce an erroneous population (e.g., not all
+ individuals will have been reevaluated, etc.). However, this approach
+ can be viable if solutions have been archived such that the current
+ population is not of critical importance.

"""
pass
@@ -214,7 +215,7 @@
until after the ``evolve`` method executes:

- *termination_cause* -- the name of the function causing
- ``evolve`` to terminate
+ ``evolve`` to terminate, in the event that multiple terminators are
used
- *generator* -- the generator function passed to ``evolve``
- *evaluator* -- the evaluator function passed to ``evolve``
- *bounder* -- the bounding function passed to ``evolve``
@@ -273,20 +274,25 @@
self.num_evaluations = 0
self.num_generations = 0
self.logger = logging.getLogger('ecspy.ec')
+ try:
+ self.logger.addHandler(logging.NullHandler())
+ except AttributeError:
+ # If Python < 2.7, then NullHandler doesn't exist.
+ pass
self._random = random
self._kwargs = dict()

def _should_terminate(self, pop, ng, ne):
terminate = False
fname = ''
- try:
+ if isinstance(self.terminator, (list, tuple)):
for clause in self.terminator:
self.logger.debug('termination test using %s at
generation %d and evaluation %d' % (clause.__name__, ng, ne))
terminate = terminate or clause(population=pop,
num_generations=ng, num_evaluations=ne, args=self._kwargs)
if terminate:
fname = clause.__name__
break
- except TypeError:
+ else:
self.logger.debug('termination test using %s at generation %d
and evaluation %d' % (self.terminator.__name__, ng, ne))
terminate = self.terminator(population=pop,
num_generations=ng, num_evaluations=ne, args=self._kwargs)
fname = self.terminator.__name__
=======================================
--- /trunk/ecspy/migrators.py Sat Feb 4 21:42:21 2012
+++ /trunk/ecspy/migrators.py Wed Feb 8 17:16:16 2012
@@ -25,17 +25,10 @@
along with this program. If not, see
<http://www.gnu.org/licenses/>.
"""

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


-
def default_migration(random, population, args):
"""Do nothing.

@@ -98,119 +91,5 @@
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 Tue Feb 7 19:02:51 2012
+++ /trunk/ecspy/observers.py Wed Feb 8 17:16:16 2012
@@ -33,13 +33,13 @@
pass


-def screen_observer(population, num_generations, num_evaluations, args):
- """Print the output of the EC to the screen.
-
- This function displays the results of the evolutionary computation
+def stats_observer(population, num_generations, num_evaluations, args):
+ """Print the statistics of the EC to the screen.
+
+ This function displays the statistics of the evolutionary computation
to the screen. The output includes the generation number, the current
- number of evaluations, the average fitness, the maximum fitness, and
- the full population.
+ number of evaluations, the maximum fitness, the minimum fitness,
+ the average fitness, and the standard deviation.

.. Arguments:
population -- the population of Individuals
@@ -65,11 +65,30 @@
print('Generation Evaluation Worst Best Median
Average Std Dev ')
print('---------- ---------- ---------- ---------- ----------
---------- ----------')
print('{0:10} {1:10} {2:10.5} {3:10.5} {4:10.5} {5:10.5}
{6:10.5}\n'.format(num_generations, num_evaluations, worst_fit, best_fit,
med_fit, avg_fit, std_fit))
+
+
+def population_observer(population, num_generations, num_evaluations,
args):
+ """Print the current population of the EC to the screen.
+
+ This function displays the current population of the evolutionary
+ computation to the screen in fitness-sorted order.
+
+ .. Arguments:
+ population -- the population of Individuals
+ num_generations -- the number of elapsed generations
+ num_evaluations -- the number of candidate solution evaluations
+ args -- a dictionary of keyword arguments
+
+ """
+
+ population = list(population)
+ population.sort(reverse=True)
+
print('----------------------------------------------------------------------------')
print('Current Population:')
for ind in population:
print(str(ind))

print('----------------------------------------------------------------------------')
-
+

def file_observer(population, num_generations, num_evaluations, args):
"""Print the output of the EC to a file.
=======================================
--- /trunk/ecspy/replacers.py Wed Dec 15 10:05:03 2010
+++ /trunk/ecspy/replacers.py Wed Feb 8 17:16:16 2012
@@ -337,7 +337,7 @@
for p, o in zip(parents, offspring):
if o >= p:
new_pop.append(o)
- elif random.random() < math.exp(-abs(p.fitness - o.fitness) /
float(temp)):
+ elif temp > 0 and random.random() < math.exp(-abs(p.fitness -
o.fitness) / float(temp)):
new_pop.append(o)
else:
new_pop.append(p)
=======================================
--- /trunk/examples/constraint_example.py Thu Aug 19 22:26:17 2010
+++ /trunk/examples/constraint_example.py Wed Feb 8 17:16:16 2012
@@ -61,7 +61,7 @@
myec.variator = variators.gaussian_mutation
myec.replacer = replacers.generational_replacement
myec.terminator = terminators.evaluation_termination
-myec.observer = observers.screen_observer
+myec.observer = observers.stats_observer
pop = myec.evolve(my_generator, my_evaluator,
pop_size=100,
bounder=ec.Bounder([-2.0] * 2, [2.0] * 2),
=======================================
--- /trunk/examples/custom_ec_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/custom_ec_example.py Wed Feb 8 17:16:16 2012
@@ -1,25 +1,18 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import selectors
-from ecspy import replacers
-from ecspy import variators
-from ecspy import observers
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Ackley(2)
- ea = ec.EvolutionaryComputation(prng)
- ea.selector = selectors.tournament_selection
- ea.variator = [variators.uniform_crossover,
variators.gaussian_mutation]
- ea.replacer = replacers.steady_state_replacement
- ea.terminator = terminators.generation_termination
+ problem = ecspy.benchmarks.Ackley(2)
+ ea = ecspy.ec.EvolutionaryComputation(prng)
+ ea.selector = ecspy.selectors.tournament_selection
+ ea.variator = [ecspy.variators.uniform_crossover,
ecspy.variators.gaussian_mutation]
+ ea.replacer = ecspy.replacers.steady_state_replacement
+ ea.terminator = ecspy.terminators.generation_termination
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
@@ -30,33 +23,8 @@
max_generations=300,
mutation_rate=0.2)

- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 60
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/dea_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/dea_example.py Wed Feb 8 17:16:16 2012
@@ -1,19 +1,15 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import observers
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Griewank(2)
- ea = ec.DEA(prng)
- ea.terminator = terminators.evaluation_termination
+ problem = ecspy.benchmarks.Griewank(2)
+ ea = ecspy.ec.DEA(prng)
+ ea.terminator = ecspy.terminators.evaluation_termination
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
@@ -21,33 +17,8 @@
maximize=problem.maximize,
max_evaluations=30000)

- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 60
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/eda_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/eda_example.py Wed Feb 8 17:16:16 2012
@@ -1,55 +1,28 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import observers
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Rastrigin(2)
- ea = ec.EDA(prng)
- ea.terminator = terminators.evaluation_termination
+ problem = ecspy.benchmarks.Rastrigin(2)
+ ea = ecspy.ec.EDA(prng)
+ #ea.observer = ecspy.observers.stats_observer
+ ea.terminator = ecspy.terminators.evaluation_termination
final_pop = ea.evolve(evaluator=problem.evaluator,
generator=problem.generator,
pop_size=1000,
bounder=problem.bounder,
+ maximize=problem.maximize,
max_evaluations=30000,
num_selected=500,
num_offspring=1000,
num_elites=1)

- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 40
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/es_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/es_example.py Wed Feb 8 17:16:16 2012
@@ -1,18 +1,15 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Rosenbrock(2)
- ea = ec.ES(prng)
- ea.terminator = [terminators.evaluation_termination,
terminators.diversity_termination]
+ problem = ecspy.benchmarks.Rosenbrock(2)
+ ea = ecspy.ec.ES(prng)
+ ea.terminator = [ecspy.terminators.evaluation_termination,
ecspy.terminators.diversity_termination]
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
@@ -21,34 +18,8 @@
max_evaluations=30000,
mutation_rate=0.2,
use_one_fifth_rule=True)
-
- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 40
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/ga_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/ga_example.py Wed Feb 8 17:16:16 2012
@@ -1,73 +1,29 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import observers
-from ecspy import terminators
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Binary(benchmarks.Schwefel(2), dimension_bits=30)
-
- stat_file = open('ga_statistics.csv', 'w')
- ind_file = open('ga_individuals.csv', 'w')
-
- ea = ec.GA(prng)
- ea.observer = observers.file_observer
- ea.terminator = terminators.evaluation_termination
+ problem = ecspy.benchmarks.Binary(ecspy.benchmarks.Schwefel(2),
dimension_bits=30)
+ ea = ecspy.ec.GA(prng)
+ #ea.observer = ecspy.observers.stats_observer
+ ea.terminator = ecspy.terminators.evaluation_termination
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
maximize=problem.maximize,
bounder=problem.bounder,
max_evaluations=30000,
- statistics_file=stat_file,
- individuals_file=ind_file,
num_elites=1)
- stat_file.close()
- ind_file.close()
-
-
- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- realbest = problem.binary_to_real(best.candidate)
- realfit = best.fitness
- print('Converted as --> %s : %f' % (str(realbest), realfit))
-
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- from ecspy import analysis
-
- # Create the points using the original Ackley function.
- num_points = 40
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.benchmark.evaluator([[a, b] for a, b in zip(x, y)], {})
-
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([realbest[0]], [realbest[1]], [realfit], color='r')
- realopt = problem.benchmark.global_optimum
- ax.scatter3D([realopt[0]], [realopt[1]],
problem.benchmark.evaluator([realopt], {}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- analysis.generation_plot('ga_statistics.csv', errorbars=False)
+
+ # Note that the Scwefel function is a minimization problem,
+ # but the max of the final population is the "best" individual,
+ # which in this case means the individual with the smallest fitness.
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/niche_example.py Thu Aug 19 22:26:17 2010
+++ /trunk/examples/niche_example.py Wed Feb 8 17:16:16 2012
@@ -2,13 +2,7 @@
import time
import math
import itertools
-from ecspy import ec
-from ecspy import selectors
-from ecspy import terminators
-from ecspy import variators
-from ecspy import replacers
-from ecspy import observers
-
+import ecspy

def my_distance(x, y):
return sum([abs(a - b) for a, b in zip(x, y)])
@@ -16,7 +10,6 @@
def generate(random, args):
return [random.uniform(0, 26)]

-
def evaluate(candidates, args):
fitness = []
for cand in candidates:
@@ -24,19 +17,18 @@
fitness.append(fit)
return fitness

-
def main(do_plot=True, prng=None):
if prng is None:
prng = random.Random()
prng.seed(time.time())

- ea = ec.EvolutionaryComputation(prng)
- ea.selector = selectors.tournament_selection
- ea.replacer = replacers.crowding_replacement
- ea.variator = variators.gaussian_mutation
- ea.terminator = terminators.evaluation_termination
-
- final_pop = ea.evolve(generate, evaluate, pop_size=20,
bounder=ec.Bounder(0, 26),
+ ea = ecspy.ec.EvolutionaryComputation(prng)
+ ea.selector = ecspy.selectors.tournament_selection
+ ea.replacer = ecspy.replacers.crowding_replacement
+ ea.variator = ecspy.variators.gaussian_mutation
+ ea.terminator = ecspy.terminators.evaluation_termination
+
+ final_pop = ea.evolve(generate, evaluate, pop_size=20,
bounder=ecspy.ec.Bounder(0, 26),
max_evaluations=5000,
num_selected=20,
mutation_rate=1.0,
=======================================
--- /trunk/examples/nsga_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/nsga_example.py Wed Feb 8 17:16:16 2012
@@ -1,20 +1,16 @@
from random import Random
from time import time
-from ecspy import emo
-from ecspy import variators
-from ecspy import terminators
-from ecspy import benchmarks
-
+import ecspy

def main(do_plot=True, prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Kursawe(3)
- ea = emo.NSGA2(prng)
- ea.variator = [variators.blend_crossover, variators.gaussian_mutation]
- ea.terminator = terminators.generation_termination
+ problem = ecspy.benchmarks.Kursawe(3)
+ ea = ecspy.emo.NSGA2(prng)
+ ea.variator = [ecspy.variators.blend_crossover,
ecspy.variators.gaussian_mutation]
+ ea.terminator = ecspy.terminators.generation_termination
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
=======================================
--- /trunk/examples/paes_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/paes_example.py Wed Feb 8 17:16:16 2012
@@ -1,19 +1,15 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import emo
-from ecspy import terminators
-from ecspy import benchmarks
-
+import ecspy

def main(do_plot=True, prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Kursawe(3)
- ea = emo.PAES(prng)
- ea.terminator = terminators.evaluation_termination
+ problem = ecspy.benchmarks.Kursawe(3)
+ ea = ecspy.emo.PAES(prng)
+ ea.terminator = ecspy.terminators.evaluation_termination
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
bounder=problem.bounder,
=======================================
--- /trunk/examples/pso_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/pso_example.py Wed Feb 8 17:16:16 2012
@@ -1,21 +1,16 @@
from time import time
from random import Random
-from ecspy import terminators
-from ecspy import topologies
-from ecspy import swarm
-from ecspy import ec
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Sphere(2)
- ea = swarm.PSO(prng)
- ea.terminator = terminators.evaluation_termination
- ea.topology = topologies.ring_topology
+ problem = ecspy.benchmarks.Ackley(2)
+ ea = ecspy.swarm.PSO(prng)
+ ea.terminator = ecspy.terminators.evaluation_termination
+ ea.topology = ecspy.topologies.ring_topology
final_pop = ea.evolve(generator=problem.generator,
evaluator=problem.evaluator,
pop_size=100,
@@ -24,33 +19,8 @@
max_evaluations=30000,
neighborhood_size=5)

- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 40
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/examples/sa_example.py Sun Aug 22 00:13:44 2010
+++ /trunk/examples/sa_example.py Wed Feb 8 17:16:16 2012
@@ -1,51 +1,22 @@
from random import Random
from time import time
-from ecspy import ec
-from ecspy import terminators
-from ecspy import benchmarks
-
-
-def main(do_plot=True, prng=None):
+import ecspy
+
+def main(prng=None):
if prng is None:
prng = Random()
prng.seed(time())

- problem = benchmarks.Sphere(2)
- ea = ec.SA(prng)
- ea.terminator = terminators.evaluation_termination
+ problem = ecspy.benchmarks.Sphere(2)
+ ea = ecspy.ec.SA(prng)
+ ea.terminator = ecspy.terminators.evaluation_termination
final_pop = ea.evolve(evaluator=problem.evaluator,
generator=problem.generator,
maximize=problem.maximize,
bounder=problem.bounder,
max_evaluations=30000)
-
- if do_plot:
- best = max(final_pop)
- print('%s Example (%s) Best Solution: \n%s' %
(ea.__class__.__name__, problem.__class__.__name__, str(best)))
- import itertools
- import pylab
- import mpl_toolkits.mplot3d.axes3d as axes3d
- num_points = 40
- points = []
- for lb, ub in zip(problem.bounder.lower_bound,
problem.bounder.upper_bound):
- points.append([(i / float(num_points)) * (ub - lb) + lb for i
in range(num_points)])
- points = itertools.product(*points)
- x = []
- y = []
- for p in points:
- x.append(p[0])
- y.append(p[1])
- z = problem.evaluator([[a, b] for a, b in zip(x, y)], {})
- fig = pylab.figure()
- ax = axes3d.Axes3D(fig)
- ax.scatter3D(x, y, z)
- ax.scatter3D([best.candidate[0]], [best.candidate[1]],
[best.fitness], color='r')
- ax.scatter3D([problem.global_optimum[0]],
[problem.global_optimum[1]], problem.evaluator([problem.global_optimum],
{}), color='g')
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Fitness')
- pylab.savefig('%s Example (%s).pdf' % (ea.__class__.__name__,
problem.__class__.__name__), format='pdf')
- pylab.show()
+ best = max(final_pop)
+ print('%s Example (%s) Best Solution: \n%s' % (ea.__class__.__name__,
problem.__class__.__name__, str(best)))
return ea

if __name__ == '__main__':
=======================================
--- /trunk/tests/operator_tests.py Sat Feb 4 21:42:21 2012
+++ /trunk/tests/operator_tests.py Wed Feb 8 17:16:16 2012
@@ -1,4 +1,3 @@
-
import unittest
import random
import logging
@@ -20,6 +19,8 @@
for c in candidates:
fitness.append(ecspy.emo.Pareto([sum(c), sum(c)]))
return fitness
+
+

prng = random.Random()
prng.seed(111111)
@@ -72,6 +73,23 @@
def test_default_migration(self):
migrants = ecspy.migrators.default_migration(prng,
test_population, {})
assert migrants == test_population
+ '''
+ def test_multiprocessing_migration(self):
+ class fake_ec(object):
+ def __init__(self):
+ self.evaluator = test_evaluator
+ self.num_evaluations = 0
+ x = fake_ec()
+ mm = ecspy.migrators.MultiprocessingMigrator(2)
+ mig = ecspy.ec.Individual([1, 1, 1, 1, 1, 1])
+ mig.fitness = 0
+ mm.migrants.put(mig)
+ new_pop = mm(prng, test_population, {'_ec': x, 'evaluate_migrant':
True})
+ mm.migrants.join_thread()
+ assert mig.candidate in [p.candidate for p in new_pop]
+ assert mm.migrants.qsize() == 1
+ assert x.num_evaluations == 1
+ '''

class ReplacerTests(unittest.TestCase):
def test_default_replacement(self):
Reply all
Reply to author
Forward
0 new messages