From 131e0e033d6089acc49ff32dd2c0ffb24271d174 Mon Sep 17 00:00:00 2001 From: maartenkeijzer Date: Sun, 5 Jan 2003 16:31:50 +0000 Subject: [PATCH] Added pyeo. Some changes needed to be made for include files and the like in some files (and some bugs were fixed as well [Marc: eoOneToOneBreeder was a mess]) eoFunctor.h now contains static functor_category members, this shouldn't hurt anyone. --- eo/src/EO.h | 3 - eo/src/Makefile.am | 4 +- eo/src/eoDetTournamentSelect.h | 2 +- eo/src/eoFunctor.h | 17 +- eo/src/eoGenOp.h | 8 +- eo/src/eoOneToOneBreeder.h | 7 +- eo/src/eoOpContainer.h | 2 +- eo/src/eoTruncSelect.h | 2 +- eo/src/pyeo/AUTHORS | 3 + eo/src/pyeo/COPYING | 340 +++++++++++++++++++++++++++++ eo/src/pyeo/Makefile | 48 ++++ eo/src/pyeo/NEWS | 0 eo/src/pyeo/README | 3 + eo/src/pyeo/abstract1.cpp | 43 ++++ eo/src/pyeo/algos.cpp | 93 ++++++++ eo/src/pyeo/breeders.cpp | 49 +++++ eo/src/pyeo/continuators.cpp | 63 ++++++ eo/src/pyeo/def_abstract_functor.h | 135 ++++++++++++ eo/src/pyeo/geneticOps.cpp | 155 +++++++++++++ eo/src/pyeo/mergers.cpp | 39 ++++ eo/src/pyeo/monitors.cpp | 28 +++ eo/src/pyeo/perf2worth.cpp | 30 +++ eo/src/pyeo/pickle.h | 67 ++++++ eo/src/pyeo/pyeo.cpp | 173 +++++++++++++++ eo/src/pyeo/pyeo.h | 117 ++++++++++ eo/src/pyeo/random_numbers.cpp | 66 ++++++ eo/src/pyeo/reduce.cpp | 63 ++++++ eo/src/pyeo/replacement.cpp | 65 ++++++ eo/src/pyeo/selectOne.cpp | 104 +++++++++ eo/src/pyeo/selectors.cpp | 59 +++++ eo/src/pyeo/test/maxone.py | 81 +++++++ eo/src/pyeo/test/run_tests.sh | 8 + eo/src/pyeo/test/test_breeders.py | 37 ++++ eo/src/pyeo/test/test_pickling.py | 102 +++++++++ eo/src/pyeo/test/test_populator.py | 86 ++++++++ eo/src/pyeo/test/test_reduce.py | 34 +++ eo/src/pyeo/test/test_selectone.py | 66 ++++++ eo/src/pyeo/test/test_sga.py | 25 +++ eo/src/pyeo/valueParam.cpp | 85 ++++++++ eo/src/utils/selectors.h | 6 +- 40 files changed, 2300 insertions(+), 18 deletions(-) create mode 100644 eo/src/pyeo/AUTHORS create mode 100644 eo/src/pyeo/COPYING create mode 100644 eo/src/pyeo/Makefile create mode 100644 eo/src/pyeo/NEWS create mode 100644 eo/src/pyeo/README create mode 100644 eo/src/pyeo/abstract1.cpp create mode 100644 eo/src/pyeo/algos.cpp create mode 100644 eo/src/pyeo/breeders.cpp create mode 100644 eo/src/pyeo/continuators.cpp create mode 100644 eo/src/pyeo/def_abstract_functor.h create mode 100644 eo/src/pyeo/geneticOps.cpp create mode 100644 eo/src/pyeo/mergers.cpp create mode 100644 eo/src/pyeo/monitors.cpp create mode 100644 eo/src/pyeo/perf2worth.cpp create mode 100644 eo/src/pyeo/pickle.h create mode 100644 eo/src/pyeo/pyeo.cpp create mode 100644 eo/src/pyeo/pyeo.h create mode 100644 eo/src/pyeo/random_numbers.cpp create mode 100644 eo/src/pyeo/reduce.cpp create mode 100644 eo/src/pyeo/replacement.cpp create mode 100644 eo/src/pyeo/selectOne.cpp create mode 100644 eo/src/pyeo/selectors.cpp create mode 100644 eo/src/pyeo/test/maxone.py create mode 100755 eo/src/pyeo/test/run_tests.sh create mode 100644 eo/src/pyeo/test/test_breeders.py create mode 100644 eo/src/pyeo/test/test_pickling.py create mode 100644 eo/src/pyeo/test/test_populator.py create mode 100644 eo/src/pyeo/test/test_reduce.py create mode 100644 eo/src/pyeo/test/test_selectone.py create mode 100644 eo/src/pyeo/test/test_sga.py create mode 100644 eo/src/pyeo/valueParam.cpp diff --git a/eo/src/EO.h b/eo/src/EO.h index a1147b1d..7613d91c 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -120,9 +120,6 @@ public: _is.seekg(pos); // rewind _is >> repFitness; } - - - } /** diff --git a/eo/src/Makefile.am b/eo/src/Makefile.am index 88ca6f32..e37a7007 100644 --- a/eo/src/Makefile.am +++ b/eo/src/Makefile.am @@ -4,12 +4,12 @@ ## ############################################################################### -SUBDIRS = es ga gp utils other +SUBDIRS = es ga gp utils other do CPPFLAGS = -O2 lib_LIBRARIES = libeo.a libeo_a_SOURCES = eoFunctorStore.cpp eoPersistent.cpp eoPrintable.cpp eoCtrlCContinue.cpp eoParetoFitness.cpp libeoincdir = $(includedir)/eo -libeoinc_HEADERS = *.h eo +libeoinc_HEADERS = *.h eo do/*.h diff --git a/eo/src/eoDetTournamentSelect.h b/eo/src/eoDetTournamentSelect.h index 7bd272a7..5c72031c 100755 --- a/eo/src/eoDetTournamentSelect.h +++ b/eo/src/eoDetTournamentSelect.h @@ -60,7 +60,7 @@ template class eoDetTournamentSelect: public eoSelectOne */ virtual const EOT& operator()(const eoPop& _pop) { - return deterministic_tournament(_pop, tSize); + return deterministic_tournament(_pop, tSize); } private: diff --git a/eo/src/eoFunctor.h b/eo/src/eoFunctor.h index ebce1279..3d060a73 100644 --- a/eo/src/eoFunctor.h +++ b/eo/src/eoFunctor.h @@ -20,7 +20,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es mak@dhi.dk - CVS Info: $Date: 2001-03-21 12:10:13 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.5 2001-03-21 12:10:13 jmerelo Exp $ $Author: jmerelo $ + CVS Info: $Date: 2003-01-05 16:31:47 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.6 2003-01-05 16:31:47 maartenkeijzer Exp $ $Author: maartenkeijzer $ */ //----------------------------------------------------------------------------- @@ -75,6 +75,11 @@ public : /// The pure virtual function that needs to be implemented by the subclass virtual R operator()() = 0; + + static eoFunctorBase::procedure_tag functor_category() + { + return eoFunctorBase::procedure_tag(); + } }; /** @@ -106,6 +111,11 @@ public : /// The pure virtual function that needs to be implemented by the subclass virtual R operator()(A1) = 0; + + static eoFunctorBase::unary_function_tag functor_category() + { + return eoFunctorBase::unary_function_tag(); + } }; /** @@ -140,6 +150,11 @@ public : /// The pure virtual function that needs to be implemented by the subclass virtual R operator()(A1, A2) = 0; + + static eoFunctorBase::binary_function_tag functor_category() + { + return eoFunctorBase::binary_function_tag(); + } }; /** diff --git a/eo/src/eoGenOp.h b/eo/src/eoGenOp.h index 74b0bc2c..9dcf6126 100644 --- a/eo/src/eoGenOp.h +++ b/eo/src/eoGenOp.h @@ -67,7 +67,7 @@ class eoGenOp : public eoOp, public eoUF &, void> virtual string className() const = 0; void operator()(eoPopulator& _pop) { - _pop.reserve(max_production()); + _pop.reserve(max_production()); apply(_pop); } @@ -163,13 +163,15 @@ class eoQuadGenOp : public eoGenOp void apply(eoPopulator& _pop) { EOT& a = *_pop; - EOT& b = *++_pop; - + EOT& b = *++_pop; + + if(op(a, b)) { a.invalidate(); b.invalidate(); } + } virtual string className() const {return op.className();} diff --git a/eo/src/eoOneToOneBreeder.h b/eo/src/eoOneToOneBreeder.h index 7b85d869..09891a71 100644 --- a/eo/src/eoOneToOneBreeder.h +++ b/eo/src/eoOneToOneBreeder.h @@ -32,7 +32,10 @@ #include #include #include +#include #include +#include +#include #include /***************************************************************************** @@ -79,7 +82,7 @@ class eoOneToOneBreeder: public eoBreed _offspring.clear(); eoSelectivePopulator popit(_parents, _offspring, select); - for (unsigned iParent=0; iParent<_parents.size(); iParent++) + for (unsigned iParent=0; iParent if (theParent > leOffspring) // old parent better than offspring if (rng.uniform() < pReplace) // if probability leOffspring = theParent; // replace - cout << "============ Final =========================\n"; - cout << _offspring << endl; // finally, go to next guy to handle ++popit; } diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h index 43465adb..5dbd4569 100644 --- a/eo/src/eoOpContainer.h +++ b/eo/src/eoOpContainer.h @@ -93,7 +93,7 @@ class eoSequentialOp : public eoOpContainer void apply(eoPopulator& _pop) { - position_type pos = _pop.tellp(); + position_type pos = _pop.tellp(); for (size_t i = 0; i < rates.size(); ++i) { diff --git a/eo/src/eoTruncSelect.h b/eo/src/eoTruncSelect.h index 313d3c2d..0c64e162 100644 --- a/eo/src/eoTruncSelect.h +++ b/eo/src/eoTruncSelect.h @@ -44,7 +44,7 @@ class eoTruncSelect : public eoSelect { public: /** Ctor: from an eoSelect (and an eoMany to tell how many are kept for selectino */ - eoSelectMany(eoSelectOne& _select, eoHowMany _howMany) + eoTruncSelect(eoSelectOne& _select, eoHowMany _howMany) : select(_select), howMany(_howMany) {} /** diff --git a/eo/src/pyeo/AUTHORS b/eo/src/pyeo/AUTHORS new file mode 100644 index 00000000..e1d90996 --- /dev/null +++ b/eo/src/pyeo/AUTHORS @@ -0,0 +1,3 @@ + +Maarten Keijzer (mkeijzer@cs.vu.nl) + diff --git a/eo/src/pyeo/COPYING b/eo/src/pyeo/COPYING new file mode 100644 index 00000000..d60c31a9 --- /dev/null +++ b/eo/src/pyeo/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/eo/src/pyeo/Makefile b/eo/src/pyeo/Makefile new file mode 100644 index 00000000..340dc7ae --- /dev/null +++ b/eo/src/pyeo/Makefile @@ -0,0 +1,48 @@ +# Note for however is foolish enough to attempt to build this thing +# +# You need: +# Python 2.2 +# Stlport +# Boost.Python v2 +# +# +# On my debian (unstable), I used libstlport_gcc.so.4.5 +# and libboost_python.so.1.29.0 +# +# Obviously together with python2.2 (as Boost.Python.v2 needs that) +# +# I'm pretty sure any stlport will do, but less convinced about boost.python +# That lib seems to be pretty much under development (as I found out, the hard way) +# but this version 1.29 seems to work for me. +# +# My version of boost was found in /usr/include, modify INC to your system + + +CXX = g++ #-3.2 +CXXFLAGS = -g #-DNDEBUG +CPPFLAGS = -Wall #-O2 +LDFLAGS = +COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c +LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) +INC=-I/usr/include/python2.2/ -I/usr/include/stlport -I.. -ftemplate-depth-50 + +OBJECTS=eoFunctorStore.o pyeo.o abstract1.o algos.o \ + random_numbers.o geneticOps.o selectOne.o continuators.o\ + reduce.o replacement.o selectors.o breeders.o\ + mergers.o valueParam.o perf2worth.o + +all: pyeo.so + +clean: + rm *.so *.o test/*.pyc + +pyeo.so: $(OBJECTS) + $(LINK) -o pyeo.so $(OBJECTS) -lboost_python -lpython2.2 -shared -lstlport + +eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp + $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) + +%.o:%.cpp pyeo.h def_abstract_functor.h + $(COMPILE) $< $(INC) + + diff --git a/eo/src/pyeo/NEWS b/eo/src/pyeo/NEWS new file mode 100644 index 00000000..e69de29b diff --git a/eo/src/pyeo/README b/eo/src/pyeo/README new file mode 100644 index 00000000..b28b04f6 --- /dev/null +++ b/eo/src/pyeo/README @@ -0,0 +1,3 @@ + + + diff --git a/eo/src/pyeo/abstract1.cpp b/eo/src/pyeo/abstract1.cpp new file mode 100644 index 00000000..d35edefc --- /dev/null +++ b/eo/src/pyeo/abstract1.cpp @@ -0,0 +1,43 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +void abstract1() +{ + /* Abstract Classes: overrideble from python */ + def_abstract_functor >("eoEvalFunc"); + def_abstract_functor >("eoInit"); + + def_abstract_functor >("eoTransform"); + + class_, bases > >("eoSGATransform", + init< eoQuadOp&, double, + eoMonOp&, double>()); + + def_abstract_functor >("eoPopEvalFunc"); +} diff --git a/eo/src/pyeo/algos.cpp b/eo/src/pyeo/algos.cpp new file mode 100644 index 00000000..c375a6a0 --- /dev/null +++ b/eo/src/pyeo/algos.cpp @@ -0,0 +1,93 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +void algos() +{ + def_abstract_functor >("eoAlgo"); + + /* Algorithms */ + class_, bases >, boost::noncopyable>("eoSGA", + init&, + eoQuadOp&, float, + eoMonOp&, float, + eoEvalFunc&, + eoContinue&>()) + .def("__call__", &eoSGA::operator()) + ; + + class_, bases > >("eoEasyEA", + init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoReplacement& >() ) + .def( init< + eoContinue&, + eoPopEvalFunc&, + eoBreed&, + eoReplacement&>() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoMerge&, + eoReduce& >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoReplacement&>()) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoMerge&, + eoReduce&>()) + .def("__call__", &eoEasyEA::operator()) + ; + + /* + class_, bases< eoAlgo > >("eoCellularEasyEA", + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoBinOp&, + eoMonOp&, + eoSelectOne&>()) + .def( + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoQuadOp&, + eoMonOp&, + eoSelectOne&>()) + ; + */ +} diff --git a/eo/src/pyeo/breeders.cpp b/eo/src/pyeo/breeders.cpp new file mode 100644 index 00000000..da2b5dcc --- /dev/null +++ b/eo/src/pyeo/breeders.cpp @@ -0,0 +1,49 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoBreed::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoBreed::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoBreed::operator()) + +void breeders() +{ + def_abstract_functor >("eoBreed"); + + DEF3(eoSelectTransform, eoSelect&, eoTransform&); + + DEF3(eoGeneralBreeder, eoSelectOne&, eoGenOp&) + .def( init&, eoGenOp&, double>() ) + .def( init&, eoGenOp&, double, bool>() ) + .def( init&, eoGenOp&, eoHowMany>() ); + + + DEF3(eoOneToOneBreeder, eoGenOp&, eoEvalFunc&) + .def( init&, eoEvalFunc&, double>() ) + .def( init&, eoEvalFunc&, double, eoHowMany>() ); + +} + diff --git a/eo/src/pyeo/continuators.cpp b/eo/src/pyeo/continuators.cpp new file mode 100644 index 00000000..8a9cb4a9 --- /dev/null +++ b/eo/src/pyeo/continuators.cpp @@ -0,0 +1,63 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoContinue::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoContinue::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoContinue::operator()) + +void continuators() +{ + /* Counters, wrappers etc */ + + class_, bases > >("eoEvalFuncCounter", + init< eoEvalFunc&, std::string>()) + .def("__call__", &eoEvalFuncCounter::operator()) + ; + /* Continuators */ + def_abstract_functor >("eoContinue"); + + class_, bases >, boost::noncopyable >("eoGenContinue", init() ) + .def("__call__", &eoGenContinue::operator()) + ; + + class_, bases > >("eoCombinedContinue", init&>()) + .def( init&, eoContinue& >() ) + .def("add", &eoCombinedContinue::add) + .def("__call__", &eoCombinedContinue::operator()) + ; + + class_, bases > >("eoEvalContinue", + init&, unsigned long>()) + .def("__call__", &eoEvalContinue::operator()) + ; + + DEF2(eoFitContinue, object); // object is the fitness type + + DEF3(eoSteadyFitContinue, unsigned long, unsigned long); +} diff --git a/eo/src/pyeo/def_abstract_functor.h b/eo/src/pyeo/def_abstract_functor.h new file mode 100644 index 00000000..eaa4aa54 --- /dev/null +++ b/eo/src/pyeo/def_abstract_functor.h @@ -0,0 +1,135 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef MAKE_ABSTRACT_FUNCTOR_H +#define MAKE_ABSTRACT_FUNCTOR_H + +#include + +namespace eoutils { + +using namespace boost::python; + +template +class ProcWrapper : public Proc +{ + public: + PyObject* self; + ProcWrapper(PyObject* s) : self(s) {} + + typename Proc::result_type operator()(void) + { + return boost::python::call_method(self, "__call__"); + } +}; + +template +void make_abstract_functor(std::string name, typename eoFunctorBase::procedure_tag) +{ + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); +} + +template +void make_abstract_functor_ref(std::string name, typename eoFunctorBase::procedure_tag) +{ + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>()); +} + +template +class UnaryWrapper : public Unary +{ + public: + PyObject* self; + UnaryWrapper(PyObject* s) : self(s) {} + + typename Unary::result_type operator()(typename Unary::argument_type a) + { + return boost::python::call_method(self, "__call__", boost::ref(a) ); + } +}; + +template +void make_abstract_functor(std::string name, typename eoFunctorBase::unary_function_tag) +{ + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()) + ; +} + +template +void make_abstract_functor_ref(std::string name, typename eoFunctorBase::unary_function_tag) +{ + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ) + ; +} + +template +class BinaryWrapper : public Binary +{ + public: + PyObject* self; + BinaryWrapper(PyObject* s) : self(s) {} + typename Binary::result_type operator()(typename Binary::first_argument_type a1, typename Binary::second_argument_type a2) + { + return boost::python::call_method< + typename Binary::result_type>(self, "__call__", boost::ref(a1), boost::ref(a2) ); + } +}; + +template +void make_abstract_functor(std::string name, typename eoFunctorBase::binary_function_tag) +{ + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); +} + +template +void make_abstract_functor_ref(std::string name, typename eoFunctorBase::binary_function_tag) +{ + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ); +} + +}// namespace eoutils + +template +void def_abstract_functor(std::string name) +{ + eoutils::make_abstract_functor(name, Functor::functor_category()); +} + +template +void def_abstract_functor_ref(std::string name) +{ + eoutils::make_abstract_functor_ref(name, Functor::functor_category()); +} + +#endif diff --git a/eo/src/pyeo/geneticOps.cpp b/eo/src/pyeo/geneticOps.cpp new file mode 100644 index 00000000..85f5f84e --- /dev/null +++ b/eo/src/pyeo/geneticOps.cpp @@ -0,0 +1,155 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include + +#include "pyeo.h" + +class GenOpWrapper : public eoGenOp +{ + public: + + PyObject* self; + GenOpWrapper(PyObject* p) : self(p) {} + unsigned max_production(void) + { + return call_method(self,"max_production"); + } + std::string className() const + { + return "GenOpDerivative"; // never saw the use of className anyway + } + + void apply(eoPopulator& populator ) + { + boost::python::call_method(self,"apply", boost::ref( populator ) ); + } +}; + +class PopulatorWrapper : public eoPopulator +{ +public: + PyObject* self; + PopulatorWrapper(PyObject* p, const eoPop& src, eoPop& dest) + : eoPopulator(src, dest), self(p) + { + //throw std::runtime_error("abstract base class"); + } + + const PyEO& select() + { + return call_method(self,"select"); + } +}; + +class MonOpWrapper : public eoMonOp +{ +public: + PyObject* self; + MonOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo) + { return boost::python::call_method(self, "__call__", boost::ref( _eo )); } +}; +class BinOpWrapper : public eoBinOp +{ +public: + PyObject* self; + BinOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo, const PyEO& _eo2) + { return boost::python::call_method(self, "__call__", boost::ref( _eo ), boost::ref(_eo2)); } +}; +class QuadOpWrapper : public eoQuadOp +{ +public: + PyObject* self; + QuadOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo, PyEO& _eo2) + { return boost::python::call_method(self, "__call__", boost::ref( _eo ), boost::ref(_eo2)); } +}; + +void geneticOps() +{ + class_, PopulatorWrapper, boost::noncopyable> + ("eoPopulator", init&, eoPop&>() ) + .def("select", &PopulatorWrapper::select, return_internal_reference<>() ) + .def("get", &eoPopulator::operator*, return_internal_reference<>() ) + .def("next", &eoPopulator::operator++, return_internal_reference<>() ) + .def("insert", &eoPopulator::insert) + .def("reserve", &eoPopulator::reserve) + .def("source", &eoPopulator::source, return_internal_reference<>() ) + .def("offspring", &eoPopulator::offspring, return_internal_reference<>() ) + .def("tellp", &eoPopulator::tellp) + .def("seekp", &eoPopulator::seekp) + .def("exhausted", &eoPopulator::exhausted) + ; + + class_, bases > > + ("eoSeqPopulator", init&, eoPop&>() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; + + class_, bases > > + ("eoSelectivePopulator", init&, eoPop&, eoSelectOne& >() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; + enum_::OpType>("OpType") + .value("unary", eoOp::unary) + .value("binary", eoOp::binary) + .value("quadratic", eoOp::quadratic) + .value("general", eoOp::general) + ; + + class_ >("eoOp", init::OpType>()) + .def("getType", &eoOp::getType); + + class_, MonOpWrapper, bases >, boost::noncopyable>("eoMonOp", init<>()) + .def("__call__", &MonOpWrapper::operator(), "an example docstring"); + class_, BinOpWrapper, bases >, boost::noncopyable>("eoBinOp", init<>()) + .def("__call__", &BinOpWrapper::operator()); + class_, QuadOpWrapper, bases >, boost::noncopyable>("eoQuadOp", init<>()) + .def("__call__", &QuadOpWrapper::operator()); + + class_, GenOpWrapper, bases >, boost::noncopyable>("eoGenOp", init<>()) + .def("max_production", &GenOpWrapper::max_production) + .def("className", &GenOpWrapper::className) + .def("apply", &GenOpWrapper::apply) + .def("__call__", &eoGenOp::operator()) + ; + + class_, bases >, boost::noncopyable>("eoSequentialOp", init<>()) + .def("add", &eoSequentialOp::add) + .def("apply", &eoSequentialOp::apply) + ; + + class_, bases >, boost::noncopyable>("eoProportionalOp", init<>()) + .def("add", &eoProportionalOp::add) + .def("apply", &eoProportionalOp::apply) + ; + + /* Cloning */ + class_, bases > >("eoMonCloneOp").def("__call__", &eoMonCloneOp::operator()); + class_, bases > >("eoBinCloneOp").def("__call__", &eoBinCloneOp::operator()); + class_, bases > >("eoQuadCloneOp").def("__call__", &eoQuadCloneOp::operator()); + +} diff --git a/eo/src/pyeo/mergers.cpp b/eo/src/pyeo/mergers.cpp new file mode 100644 index 00000000..1106b663 --- /dev/null +++ b/eo/src/pyeo/mergers.cpp @@ -0,0 +1,39 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include "pyeo.h" +#include "def_abstract_functor.h" + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoMerge::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoMerge::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoMerge::operator()) + +void mergers() +{ + def_abstract_functor >("eoMerge"); + + DEF2(eoElitism, double) + .def( init() ); + DEF(eoNoElitism); + DEF(eoPlus); + +} + diff --git a/eo/src/pyeo/monitors.cpp b/eo/src/pyeo/monitors.cpp new file mode 100644 index 00000000..e15f091b --- /dev/null +++ b/eo/src/pyeo/monitors.cpp @@ -0,0 +1,28 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include "pyeo.h" + +void monitors() +{ + +} + diff --git a/eo/src/pyeo/perf2worth.cpp b/eo/src/pyeo/perf2worth.cpp new file mode 100644 index 00000000..5ef8630d --- /dev/null +++ b/eo/src/pyeo/perf2worth.cpp @@ -0,0 +1,30 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ +//#include +//#include + +//#include "pyeo.h" + +void perf2worth() // will have to rethink this +{ + // class_ >("eoNDSorting_II"); +} + + diff --git a/eo/src/pyeo/pickle.h b/eo/src/pyeo/pickle.h new file mode 100644 index 00000000..992f04a1 --- /dev/null +++ b/eo/src/pyeo/pickle.h @@ -0,0 +1,67 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef PICKLE_H +#define PICKLE_h + +#include +#include +/** Implements pickle support for eoPersistent derivatives */ + + +template +struct T_pickle_suite : boost::python::pickle_suite +{ + static + std::string print_to_string(const T& t) + { + std::ostrstream os; + t.printOn(os); + os << ends; + return os.str(); + } + + static + boost::python::tuple getstate(const T& t) + { + std::string s = print_to_string(t); + return boost::python::make_tuple( boost::python::str(s)); + } + + static + void setstate(T& t, boost::python::tuple pickled) + { + std::string s = extract(pickled[0]); + std::istrstream is(s.c_str(), s.size()); + t.readFrom(is); + } +}; + +/** Defines persistency through pickle support by using strings + * so while we're at it, we will .def("__str__") as well + */ +template +boost::python::class_& pickle(boost::python::class_& c) +{ + return c.def_pickle(T_pickle_suite()) + .def("__str__", T_pickle_suite::print_to_string); +} + +#endif diff --git a/eo/src/pyeo/pyeo.cpp b/eo/src/pyeo/pyeo.cpp new file mode 100644 index 00000000..c7abcf18 --- /dev/null +++ b/eo/src/pyeo/pyeo.cpp @@ -0,0 +1,173 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +#include +#include "pyeo.h" + +ostream& operator<<(ostream& os, const PyEO& _eo) +{ + os << _eo.to_string(); + return os; +} + +struct pyPop_pickle_suite : boost::python::pickle_suite +{ + static boost::python::tuple getstate(const eoPop& _pop) + { + boost::python::list entries; + for (unsigned i = 0; i != _pop.size(); ++i) + entries.append( PyEO_pickle_suite::getstate(_pop[i]) ); + + return make_tuple(object(_pop.size()), entries); + } + + static void setstate( eoPop& _pop, boost::python::tuple pickled) + { + int sz = extract(pickled[0]); + boost::python::list entries = pickled[1]; + _pop.resize(sz); + for (unsigned i = 0; i != _pop.size(); ++i) + PyEO_pickle_suite::setstate(_pop[i], tuple(entries[i]) ); + } +}; + + +template +boost::python::str to_string(T& _p) +{ + std::ostrstream os; + _p.printOn(os); + os << ends; + std::string s(os.str()); + return str(s.c_str()); +} + +void pop_sort(eoPop& pop) { pop.sort(); } +void pop_shuffle(eoPop& pop) { pop.shuffle(); } + +struct index_error { index_error(std::string w) : what(w) {}; std::string what; }; +void translate_index_error(index_error const& e) +{ + PyErr_SetString(PyExc_IndexError, e.what.c_str()); +} + +PyEO& pop_getitem(eoPop& pop, object key) +{ + extract x(key); + if (!x.check()) + throw index_error("Slicing not allowed"); + + int i = x(); + + if (static_cast(i) >= pop.size()) + { + throw index_error("Index out of bounds"); + } + + return pop[i]; +} +void pop_setitem(eoPop& pop, object key, PyEO& value) +{ + + extract x(key); + if (!x.check()) + throw index_error("Slicing not allowed"); + + int i = x(); + + if (static_cast(i) >= pop.size()) + { + throw index_error("Index out of bounds"); + } + + pop[i] = value; +} + +void pop_push_back(eoPop& pop, PyEO& p) { pop.push_back(p); } +void pop_resize( eoPop& pop, unsigned i) { pop.resize(i); } + +extern void abstract1(); +extern void algos(); +extern void random_numbers(); +extern void geneticOps(); +extern void selectOne(); +extern void continuators(); +extern void reduce(); +extern void replacement(); +extern void selectors(); +extern void breeders(); +extern void mergers(); +extern void valueParam(); +extern void perf2worth(); + +BOOST_PYTHON_MODULE(pyeo) +{ + register_exception_translator(&translate_index_error); + + class_("EO") + .add_property("fitness", &PyEO::getFitness, &PyEO::setFitness) + .add_property("genome", &PyEO::getGenome, &PyEO::setGenome) + .def_pickle(PyEO_pickle_suite()) + .def("invalidate", &PyEO::invalidate) + .def("invalid", &PyEO::invalid) + .def("__str__", &PyEO::to_string) + ; + + class_ >("Pop", init<>() ) + .def( init< unsigned, eoInit& >() ) + .def("append", &eoPop::append) + .def("__str__", to_string >) + .def("__len__", &eoPop::size) + .def("sort", pop_sort ) + .def("shuffle", pop_shuffle) + .def("__getitem__", pop_getitem, return_internal_reference<>() ) + .def("__setitem__", pop_setitem) + .def("best", &eoPop::best_element, return_internal_reference<>() ) + .def("push_back", pop_push_back) + .def("resize", pop_resize) + .def_pickle(pyPop_pickle_suite()) + ; + + + // Other definitions in different compilation units, + // this to avoid having g++ to choke on the load + random_numbers(); + valueParam(); + abstract1(); + geneticOps(); + selectOne(); + selectors(); + perf2worth(); + continuators(); + reduce(); + replacement(); + breeders(); + mergers(); + algos(); + +} + + +// to avoid having to build with libeo.a +ostream & operator << ( ostream& _os, const eoPrintable& _o ) { + _o.printOn(_os); + return _os; +}; diff --git a/eo/src/pyeo/pyeo.h b/eo/src/pyeo/pyeo.h new file mode 100644 index 00000000..101f6d45 --- /dev/null +++ b/eo/src/pyeo/pyeo.h @@ -0,0 +1,117 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef PYEO_H +#define PYEO_H + +#include +#include + +using namespace boost::python; +/* +class PyFitness : public boost::python::object +{ + public : + PyFitness() : object() {} + + template + PyFitness(const T& o) : object(o) {} + + + static unsigned nObjectives() { return 1; } + static double tol() { return 1e-6; } + static bool maximizing(int which) { return true; } + + static bool dominates(const PyFitness& one, const PyFitness& oth) { return true; } // for the moment + + operator unsigned() const { return 1; } // for the moment + operator double() const { return 1; } // for the moment + + PyFitness operator[](int i) { return PyFitness(object::operator[](i)); } + + friend ostream& operator<<(ostream& os, const PyFitness& p) { const object& o = p; os << o; return os; } + friend istream& operator>>(istream& is, PyFitness& p) { object o; is >> o; p = o; return is; } + + typedef PyFitness AtomType; +}; + + + +object fabs(object obj) +{ + object zero(0.0); + if (obj < zero ) + return zero-obj; + return obj; +} + +object max(object a, object b) +{ + if (a < b) + return b; + return a; +} +*/ + +struct PyEO : public EO< object > +{ + typedef object Fitness; + + Fitness getFitness() const { return invalid()? Fitness(): fitness(); } + void setFitness(Fitness f) { if (f == Fitness()) invalidate(); else fitness(f); } + + object getGenome() const { return genome; } + void setGenome(object g) { genome = g; } + object genome; + + std::string to_string() const + { + std::string result; + result += extract(str(getFitness())); + result += ' '; + result += extract(str(genome)); + return result; + } + + bool operator<(const PyEO& other) const { return EO::operator<(other); } + bool operator>(const PyEO& other) const { return EO::operator>(other); } + +}; + +ostream& operator<<(ostream& os, const PyEO& _eo); + +struct PyEO_pickle_suite : boost::python::pickle_suite +{ + typedef PyEO::Fitness Fitness; + + static + boost::python::tuple getstate(const PyEO& _eo) + { + return make_tuple(_eo.getFitness(), _eo.genome); + } + static + void setstate(PyEO& _eo, boost::python::tuple pickled) + { + _eo.setFitness( Fitness(pickled[0]) ); + _eo.genome = pickled[1]; + } +}; + +#endif diff --git a/eo/src/pyeo/random_numbers.cpp b/eo/src/pyeo/random_numbers.cpp new file mode 100644 index 00000000..368ba058 --- /dev/null +++ b/eo/src/pyeo/random_numbers.cpp @@ -0,0 +1,66 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include + +#include + +using namespace boost::python; + +namespace eo +{ + eoRng rng(time(0)); +} + +eoRng& get_rng() { return rng; } +double normal(eoRng& rng) { return rng.normal(); } + +std::string rng_to_string(const eoRng& _rng) +{ + std::ostrstream os; + _rng.printOn(os); + os << std::ends; + return os.str(); +} + +void rng_from_string(eoRng& _rng, std::string s) +{ + std::istrstream is(s.c_str(), s.size()); + _rng.readFrom(is); +} + +void random_numbers() +{ + class_("eoRng", init()) + .def("flip", &eoRng::flip) + .def("random", &eoRng::random) + .def("rand", &eoRng::rand) + .def("rand_max", &eoRng::rand_max) + .def("reseed", &eoRng::reseed) + .def("uniform", &eoRng::uniform) + .def("normal", normal) + .def("negexp", &eoRng::negexp) + .def("to_string", rng_to_string) + .def("from_string", rng_from_string) + ; + + def("rng", get_rng, return_value_policy()); +} diff --git a/eo/src/pyeo/reduce.cpp b/eo/src/pyeo/reduce.cpp new file mode 100644 index 00000000..24910cac --- /dev/null +++ b/eo/src/pyeo/reduce.cpp @@ -0,0 +1,63 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include + +#include "pyeo.h" + +// unfortunately have to define it specially +class eoReduceWrapper : public eoReduce +{ + public: + PyObject* self; + eoReduceWrapper(PyObject* s) : self(s) {} + void operator()(eoPop& pop, unsigned i) + { + boost::python::call_method(self, "__call__", pop, i ); + } +}; + +void reduce() +{ + + // ref trick in def_abstract_functor does not work for unsigned int :-( + class_, eoReduceWrapper, boost::noncopyable>("eoReduce", init<>()) + .def("__call__", &eoReduceWrapper::operator()); + + class_, bases > >("eoTruncate", init<>() ) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoRandomReduce") + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoEPReduce", init()) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoLinearTruncate") + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoDetTournamentTruncate", init()) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoStochTournamentTruncate", init()) + .def("__call__", &eoReduce::operator()) + ; +} + diff --git a/eo/src/pyeo/replacement.cpp b/eo/src/pyeo/replacement.cpp new file mode 100644 index 00000000..bcf799cc --- /dev/null +++ b/eo/src/pyeo/replacement.cpp @@ -0,0 +1,65 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoReplacement::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoReplacement::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoReplacement::operator()) + +void replacement() +{ + def_abstract_functor >("eoReplacement"); + + // eoReplacement.h + DEF(eoGenerationalReplacement); + DEF2(eoWeakElitistReplacement, eoReplacement& ); + + // eoMergeReduce.h + DEF3(eoMergeReduce, eoMerge&, eoReduce& ); + DEF(eoPlusReplacement); + DEF(eoCommaReplacement); + DEF2(eoEPReplacement, unsigned); + + // eoReduceMerge.h + DEF3(eoReduceMerge, eoReduce&, eoMerge& ); + DEF(eoSSGAWorseReplacement); + DEF2(eoSSGADetTournamentReplacement, unsigned); + DEF2(eoSSGAStochTournamentReplacement, double); + + // eoReduceMergeReduce.h + class_, bases > >("eoReplacement", + init&, + eoHowMany, eoReduce&, eoReduce&>()) + .def("__call__", &eoReplacement::operator()); + + //eoMGGReplacement + DEF(eoMGGReplacement) + .def( init() ) + .def( init() ); +} + diff --git a/eo/src/pyeo/selectOne.cpp b/eo/src/pyeo/selectOne.cpp new file mode 100644 index 00000000..42bf0f96 --- /dev/null +++ b/eo/src/pyeo/selectOne.cpp @@ -0,0 +1,104 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include +#include + +#include "pyeo.h" +#include "pickle.h" + +class eoSelectOneWrapper : public eoSelectOne +{ + public: + PyObject* self; + eoSelectOneWrapper(PyObject* p) : self(p) {} + const PyEO& operator()(const eoPop& pop) + { + return boost::python::call_method< const PyEO& >(self, "__call__", boost::ref(pop)); + } +}; + +template +void add_select(std::string name) +{ + class_ > >(name.c_str(), init<>() ) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + ; +} + +template +void add_select(std::string name, Init init) +{ + class_ > >(name.c_str(), init) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + ; +} + +template +void add_select(std::string name, Init1 init1, Init2 init2) +{ + class_ > >(name.c_str(), init1) + .def( init2 ) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + .def("setup", &Select::setup); +} + +void selectOne() +{ + /* Concrete classes */ + + pickle(class_("eoHowMany", init<>()) + .def( init() ) + .def( init() ) + .def( init() ) + .def("__call__", &eoHowMany::operator()) + .def("__neg__", &eoHowMany::operator-) + ); + + class_, eoSelectOneWrapper, boost::noncopyable>("eoSelectOne", init<>()) + .def("__call__", &eoSelectOneWrapper::operator(), return_internal_reference<>() ) + .def("setup", &eoSelectOne::setup); + + /* SelectOne derived classes */ + + add_select >("eoDetTournamentSelect", init<>(), init() ); + add_select >("eoStochTournamentSelect", init<>(), init() ); + add_select >("eoTruncatedSelectOne", + init&, double>(), init&, eoHowMany >() ); + + // eoProportionalSelect is not feasible to implement at this point as fitness is not recognizable as a float + // use eoDetTournament instead: with a t-size of 2 it is equivalent to eoProportional with linear scaling + //add_select >("eoProportionalSelect", init&>() ); + + add_select >("eoRandomSelect"); + add_select >("eoBestSelect"); + add_select >("eoNoSelect"); + + add_select >("eoSequentialSelect", init<>(), init()); + add_select >("eoEliteSequentialSelect"); + /* + * eoSelectFromWorth.h:class eoSelectFromWorth : public eoSelectOne + + */ +} diff --git a/eo/src/pyeo/selectors.cpp b/eo/src/pyeo/selectors.cpp new file mode 100644 index 00000000..aeb333f4 --- /dev/null +++ b/eo/src/pyeo/selectors.cpp @@ -0,0 +1,59 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "pyeo.h" +#include "def_abstract_functor.h" + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoSelect::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoSelect::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoSelect::operator()) + +void selectors() +{ + def_abstract_functor >("eoSelect"); + + DEF(eoDetSelect).def( init() ).def( init() ); + DEF3(eoSelectMany, eoSelectOne&, double) + .def( init< eoSelectOne&, double, bool>() ) + .def( init< eoSelectOne&, eoHowMany>() ); + + DEF2(eoSelectNumber, eoSelectOne&) + .def( init< eoSelectOne&, unsigned>()); + + DEF2(eoSelectPerc, eoSelectOne&) + .def( init&, float>() ); + + DEF3(eoTruncSelect, eoSelectOne&, eoHowMany); + + class_, bases > >("eoTruncatedSelectMany", + init&, double, double> ()) + .def(init&, double, double, bool> ()) + .def(init&, double, double, bool, bool> ()) + .def(init&, eoHowMany, eoHowMany> ()); + +} diff --git a/eo/src/pyeo/test/maxone.py b/eo/src/pyeo/test/maxone.py new file mode 100644 index 00000000..6f1baefa --- /dev/null +++ b/eo/src/pyeo/test/maxone.py @@ -0,0 +1,81 @@ + +import sys +sys.path.append('..') + +print 'importing pyeo' +from pyeo import * +print 'done' + +from copy import copy + + +class EvalFunc(eoEvalFunc): + def __call__(self, eo): + eo.fitness = reduce(lambda x,y: x+y, eo.genome, 0) + +class Init(eoInit): + def __init__(self, genome_length = 10): + eoInit.__init__(self) + self.length = genome_length + def __call__(self, eo): + eo.genome = [rng().flip(0.5) for x in range(self.length)] + +class Mutate(eoMonOp): + def __call__(self, eo): + eo.genome = copy(eo.genome) + + prob = 1. / len(eo.genome) + for i in range(len(eo.genome)): + if rng().flip(0.5): + eo.genome[i] = 1-eo.genome[i]; + return 1 + +class Crossover(eoQuadOp): + def __call__(self, eo1, eo2): + eo1.genome = copy(eo1.genome); + eo2.genome = copy(eo2.genome); + + point = rng().random( len(eo1.genome) ); + + eo1.genome[:point] = eo2.genome[:point]; + eo2.genome[point:] = eo1.genome[point:]; + + return 1 + +evaluate = EvalFunc() +init = Init(3) +mutate = Mutate() +xover = Crossover() + +if __name__ == '__main__': + + eo = EO() + eo1 = EO() + + init(eo1) + init(eo) + evaluate(eo) + print eo + + for i in range(10): + xover(eo, eo1) + mutate(eo) + + evaluate(eo) + print eo, eo1 + + print + print + print + + pop = Pop(1, init) + + pop[0] = eo; + + mutate(pop[0]) + pop[0].invalidate() + evaluate(pop[0]) + + print pop[0], eo + + diff --git a/eo/src/pyeo/test/run_tests.sh b/eo/src/pyeo/test/run_tests.sh new file mode 100755 index 00000000..dbeb34dc --- /dev/null +++ b/eo/src/pyeo/test/run_tests.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +for i in *.py +do + python $i +done + + diff --git a/eo/src/pyeo/test/test_breeders.py b/eo/src/pyeo/test/test_breeders.py new file mode 100644 index 00000000..3e022981 --- /dev/null +++ b/eo/src/pyeo/test/test_breeders.py @@ -0,0 +1,37 @@ +from maxone import * +import unittest + +evaluate = EvalFunc() +init = Init(20) +mutate = Mutate() +xover = Crossover() + +class TestSGA(unittest.TestCase): + + def runtest(self, breed): + + pop = Pop(50, init) + for indy in pop: evaluate(indy) + + newpop = Pop(); + + breed(pop,newpop) + + print pop.best() + for indy in newpop: evaluate(indy) + print newpop.best() + + def testGeneralBreeder(self): + + seq = eoSequentialOp(); + seq.add(xover, 0.7) + seq.add(mutate, 0.9) + + sel = eoDetTournamentSelect(3) + + breed = eoGeneralBreeder(sel, seq) + + self.runtest(breed) + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/test/test_pickling.py b/eo/src/pyeo/test/test_pickling.py new file mode 100644 index 00000000..8645d061 --- /dev/null +++ b/eo/src/pyeo/test/test_pickling.py @@ -0,0 +1,102 @@ +from maxone import * +import unittest +import cPickle +import tempfile +import os + +class TestPickling(unittest.TestCase): + + def do_pickle(self, object): + + filename = tempfile.mktemp() + file = open(filename, 'wb') + pickler = cPickle.Pickler(file) + + pickler.dump(object); + del pickler + file.close() + + file = open(filename) + + unpickler = cPickle.Unpickler(file) + + object2 = unpickler.load() + + del unpickler + file.close() + os.remove(filename) + + return object2 + + def testInvalidEO(self): + + eo = EO(); + eo.genome = [1,2,3]; + + eo2 = self.do_pickle(eo) + self.failUnlessEqual( str(eo), str(eo2) ) + + def testValidEO(self): + + eo = EO(); + eo.genome = [1,2,3]; + eo.fitness = 10 + + eo2 = self.do_pickle(eo) + + self.failUnlessEqual( str(eo), str(eo2) ) + + def testPop(self): + + pop = Pop(40, init) + for indy in pop: + evaluate(indy) + + pop2 = self.do_pickle(pop) + + self.failUnlessEqual( str(pop), str(pop2) ) + + def testHowMany(self): + + howmany = eoHowMany(0.8); + howmany2 = self.do_pickle(howmany) + + self.failUnlessEqual(howmany(10), howmany2(10)) + self.failUnlessEqual( str(howmany), str(howmany) ) + + def testRNG(self): + + for i in range(10): + rng().rand() + + filename = tempfile.mktemp() + file = open(filename, 'wb') + pickler = cPickle.Pickler(file) + + s = rng().to_string() + + pickler.dump(s); + del pickler + file.close() + + file = open(filename) + + unpickler = cPickle.Unpickler(file) + + s = unpickler.load() + + rng2 = eoRng(1) + rng2.from_string(s) + + del unpickler + file.close() + os.remove(filename) + + for i in range(100): + a = rng().rand() + b = rng2.rand() + self.failUnlessEqual(a,b) + + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/test/test_populator.py b/eo/src/pyeo/test/test_populator.py new file mode 100644 index 00000000..78846b93 --- /dev/null +++ b/eo/src/pyeo/test/test_populator.py @@ -0,0 +1,86 @@ +print 'importing maxone' +from maxone import * +print 'done' +import unittest + +class Mut(Mutate): + def __init__(self): + Mutate.__init__(self) + self.cnt = 0; + def __call__(self, eo): + self.cnt += 1; + return Mutate.__call__(self, eo) + +class Xover(Crossover): + def __init__(self): + Crossover.__init__(self) + self.cnt = 0; + def __call__(self, eo1, eo2): + self.cnt += 1; + return Crossover.__call__(self, eo1, eo2) + +class TestPopulator(unittest.TestCase): + + def make_pop(self): + pop = Pop(20, init) + for indy in pop: evaluate(indy) + return pop + + def test_sequential(self): + pop = self.make_pop() + populator = eoSeqPopulator(pop, pop) + + print populator.get() + print populator.get() + + def test_selective(self): + sel = eoDetTournamentSelect(2) + pop = self.make_pop() + + populator = eoSelectivePopulator(pop, pop, sel) + + print populator.get() + print populator.get() + + def runOpContainer(self, opcontainer): + + mutate = Mut() + xover = Xover() + + print 'making seq' + seq = opcontainer() + + print "xovertype", xover.getType() + print "mutationtype", mutate.getType() + + seq.add(mutate, 0.4) + seq.add(xover, 0.8) + + pop = self.make_pop(); + offspring = Pop() + + sel = eoDetTournamentSelect(2) + + print "making populator" + populator = eoSelectivePopulator(pop, offspring, sel) + print 'made' + + for i in xrange(1000): + seq(populator) + + print mutate.cnt + print xover.cnt + + + def test_sequentialOp(self): + print '*'*20, "SequentialOp", '*'*20 + self.runOpContainer(eoSequentialOp) + + def test_proportionalOp(self): + print '*'*20, "ProportionalOp", '*'*20 + self.runOpContainer(eoProportionalOp) + + + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/test/test_reduce.py b/eo/src/pyeo/test/test_reduce.py new file mode 100644 index 00000000..d0fcd864 --- /dev/null +++ b/eo/src/pyeo/test/test_reduce.py @@ -0,0 +1,34 @@ +from maxone import * +import unittest + +class TestReduce(unittest.TestCase): + + def run_test(self, ReduceClass, Arg = None): + pop = Pop(10, init) + for indy in pop: evaluate(indy) + + if Arg: + red = ReduceClass(Arg) + else: + red = ReduceClass() + + red(pop, 5); + + self.failUnlessEqual( len(pop), 5) + + def test_eoTruncate(self): + self.run_test(eoTruncate) + def test_eoRandomeReduce(self): + self.run_test(eoRandomReduce) + def test_eoEPRReduce(self): + self.run_test(eoEPReduce, 2) + def test_eoLinearTruncate(self): + self.run_test(eoLinearTruncate) + def test_eoDetTournamentTruncate(self): + self.run_test(eoDetTournamentTruncate, 2) + def test_eoStochTournamentTruncate(self): + self.run_test(eoStochTournamentTruncate, 0.9) + + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/test/test_selectone.py b/eo/src/pyeo/test/test_selectone.py new file mode 100644 index 00000000..b756753c --- /dev/null +++ b/eo/src/pyeo/test/test_selectone.py @@ -0,0 +1,66 @@ +from maxone import * +import unittest + +class Init(eoInit): + def __call__(self, eo): + pass + +class TestSGA(unittest.TestCase): + + def __init__(self, a): + unittest.TestCase.__init__(self, a) + self.pop = Pop(4, Init()) + + for i in range(len(self.pop)): + self.pop[i].fitness = i; + + + def do_test(self, selectOne): + + print '*'*20, "Testing", str(selectOne.__class__), '*'*20 + selection = [0. for i in range(len(self.pop))] + + nTries = 500 + for i in range(nTries): + selection[ selectOne(self.pop).fitness ] += 1 + + for i in range(len(self.pop)): + print i, selection[i], selection[i] / nTries + + return selection, nTries + + def test_eoDetTournamenSelect(self): + + selectOne = eoDetTournamentSelect(2) + self.do_test(selectOne) + + def test_eoRandomSelect(self): + selectOne = eoRandomSelect() + self.do_test(selectOne) + + def test_eoBestSelect(self): + selectOne = eoBestSelect() + (sel, nTries) = self.do_test(selectOne) + + self.failUnlessEqual(sel[0], 0); + self.failUnlessEqual(sel[-1], nTries); + + def test_eoNoSelect(self): + selectOne = eoNoSelect() + self.do_test(selectOne) + + def test_eoStochTournament(self): + selectOne = eoStochTournamentSelect(0.75) + self.do_test(selectOne) + + def test_eoSequentialSelect(self): + selectOne = eoSequentialSelect(); + self.do_test(selectOne) + + def test_eoEliteSequentialSelect(self): + selectOne = eoEliteSequentialSelect(); + self.do_test(selectOne) + + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/test/test_sga.py b/eo/src/pyeo/test/test_sga.py new file mode 100644 index 00000000..b31a5fae --- /dev/null +++ b/eo/src/pyeo/test/test_sga.py @@ -0,0 +1,25 @@ +from maxone import * +import unittest + +class TestSGA(unittest.TestCase): + + def test(self): + evaluate = EvalFunc() + init = Init(20) + mutate = Mutate() + xover = Crossover() + + pop = Pop(50, init) + for indy in pop: evaluate(indy) + + select = eoDetTournamentSelect(3); + cont = eoGenContinue(20); + + sga = eoSGA(select, xover, 0.6, mutate, 0.4, evaluate, cont); + + sga(pop) + + print pop.best() + +if __name__=='__main__': + unittest.main() diff --git a/eo/src/pyeo/valueParam.cpp b/eo/src/pyeo/valueParam.cpp new file mode 100644 index 00000000..2b7eb36f --- /dev/null +++ b/eo/src/pyeo/valueParam.cpp @@ -0,0 +1,85 @@ +/* + pyeo + + Copyright (C) 2003 Maarten Keijzer + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include + +using namespace boost::python; + +class ParamWrapper : public eoParam +{ +public: + PyObject* self; + ParamWrapper(PyObject* p) : self(p) {} + ParamWrapper(PyObject* p, + std::string a, + std::string b, + std::string c, + char d, + bool e) : eoParam(a,b,c,d,e), self(p) {} + + + std::string getValue() const + { + return call_method(self, "getValue"); + } + + void setValue(std::string s) + { + call_method(self, "setValue", s); + } + +}; + +template T getv(const eoValueParam& v) { return v.value(); } +template void setv(eoValueParam& v, T val) { v.value() = val; } + +template +void define_valueParam(std::string prefix) +{ + class_, bases >( (prefix + "ValueParam").c_str(), init<>()) + .def(init()) + .def(init()) + .def(init()) + .def(init()) + .def("getValue", &eoValueParam::getValue) + .def("__str__", &eoValueParam::getValue) + .def("setValue", &eoValueParam::setValue) + //.add_property("value", getv, setv) + ; +} + +void valueParam() +{ + class_("eoParam", init<>()) + .def(init< std::string, std::string, std::string, char, bool>()) + .def("getValue", &ParamWrapper::getValue) + .def("setValue", &ParamWrapper::setValue) + .def("longName", &eoParam::longName, return_value_policy()) + //.def("defValue", &eoParam::defValue, return_value_policy()) + .def("description", &eoParam::description, return_value_policy()) + .def("shortName", &eoParam::shortName) + .def("required", &eoParam::required) + ; + + define_valueParam("int"); + define_valueParam >("vec"); +} + diff --git a/eo/src/utils/selectors.h b/eo/src/utils/selectors.h index 700cd2fb..5f63af6a 100644 --- a/eo/src/utils/selectors.h +++ b/eo/src/utils/selectors.h @@ -56,8 +56,8 @@ bool minimizing_fitness() likely not working with scalar fitness values. In that case we're sorry but you cannot use lottery or roulette_wheel selection... */ - eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this - eo2.fitness(1.0); + eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this + eo2.fitness( typename EOT::Fitness(1.0) ); return eo2 < eo1; // check whether we have a minimizing fitness }; @@ -194,7 +194,7 @@ It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = It competitor = _begin + _gen.random(_end - _begin); if (*best < *competitor) - { + { best = competitor; } }