* New tree configuration of the project:

.../
   ...           + -- EO
   |             |
   |             |
   +-- src ----- + -- EDO
   |             |
   |             |
   +-- test      + -- MO
   |             |
   |             |
   +-- tutorial  + -- MOEO
   |             |
   |             |
   +-- doc       + -- SMP
   |             |
   |             |
   ...           + -- EOMPI
                 |
                 |
                 + -- EOSERIAL

Question for current maintainers: ./README: new release?

Also:

* Moving out eompi & eoserial modules (issue #2).

* Correction of the errors when executing "make doc" command.

* Adding a solution for the conflicting headers problem (see the two CMake Cache
 Values: PROJECT_TAG & PROJECT_HRS_INSTALL_SUBPATH) (issue #1)

* Header inclusions:
        ** src: changing absolute paths into relative paths ('#include <...>' -> '#include "..."')
        ** test, tutorial: changing relative paths into absolute paths ('#include "..."' -> '#include <...>')

* Moving out some scripts from EDO -> to the root

* Add a new script for compilation and installation (see build_gcc_linux_install)

* Compilation with uBLAS library or EDO module: now ok

* Minor modifications on README & INSTALL files

* Comment eompi failed tests with no end

*** TODO: CPack (debian (DEB) & RedHat (RPM) packages) (issues #6 & #7) ***
This commit is contained in:
Adèle Harrissart 2014-08-04 13:40:28 +02:00
commit 490e837f7a
2359 changed files with 7688 additions and 16329 deletions

58
tutorial/CMakeLists.txt Executable file
View file

@ -0,0 +1,58 @@
## EO Module
if(${CMAKE_VERBOSE_MAKEFILE})
message("EO examples:")
endif(${CMAKE_VERBOSE_MAKEFILE})
add_subdirectory(${EO_TUTORIAL_DIR})
if(NOT EO_ONLY)
## MO Module
if(MO)
if(${CMAKE_VERBOSE_MAKEFILE})
message("MO examples:")
endif(${CMAKE_VERBOSE_MAKEFILE})
add_subdirectory(${MO_TUTORIAL_DIR})
endif(MO)
## EDO Module
if(EDO)
if(${CMAKE_VERBOSE_MAKEFILE})
message("EDO examples:")
endif(${CMAKE_VERBOSE_MAKEFILE})
add_subdirectory(${EDO_TUTORIAL_DIR})
endif(EDO)
## MOEO Module
if(MOEO)
if(${CMAKE_VERBOSE_MAKEFILE})
message("MOEO examples:")
endif(${CMAKE_VERBOSE_MAKEFILE})
add_subdirectory(${MOEO_TUTORIAL_DIR})
endif(MOEO)
## SMP Module
if(SMP)
if(${CMAKE_VERBOSE_MAKEFILE})
message("SMP examples:")
endif(${CMAKE_VERBOSE_MAKEFILE})
add_subdirectory(${SMP_TUTORIAL_DIR})
endif(SMP)
## EOMPI Module
#if(EOMPI)
# if(${CMAKE_VERBOSE_MAKEFILE})
# message("EOMPI examples:")
# endif(${CMAKE_VERBOSE_MAKEFILE})
# add_subdirectory(${EOMPI_TUTORIAL_DIR})
#endif(EOMPI)
## EOSERIAL Module
#if(EOSERIAL)
# if(${CMAKE_VERBOSE_MAKEFILE})
# message("EOSERIAL examples:")
# endif(${CMAKE_VERBOSE_MAKEFILE})
# add_subdirectory(${EOSERIAL_TUTORIAL_DIR})
#endif(EOSERIAL)
endif()

19
tutorial/edo/CMakeLists.txt Executable file
View file

@ -0,0 +1,19 @@
######################################################################################
### 1) Where do we go now ?!?
######################################################################################
include_directories(
#${CMAKE_CURRENT_SOURCE_DIR}/common
)
include_directories(${EIGEN3_INCLUDE_DIR})
add_subdirectory(common) # Rosenbrock and Sphere
#add_subdirectory(eda_sa)
if(EIGEN3_FOUND) # see edoNormalAdaptive
add_subdirectory(eda)
add_subdirectory(cmaes)
endif()
######################################################################################

502
tutorial/edo/COPYING Executable file
View file

@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. 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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -0,0 +1,37 @@
project(cmaes)
#find_package(Eigen3 REQUIRED)
#include_directories(EIGEN3_INCLUDE_DIR)
include_directories( ${EIGEN3_INCLUDE_DIR} )
#message( "MESSAGE:" ${EIGEN3_INCLUDE_DIR} )
#find_package(Boost 1.33.0)
#include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
#include_directories(${CMAKE_CURRENT_SOURCE_DIR})
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${EDO_SRC_DIR}/src)
#link_directories(${EO_BIN_DIRS}/${LIB})
#link_directories(${EDO_BIN_DIRS}/${LIB})
# set(RESOURCES
# ${PROJECT_NAME}.param
# )
#
# foreach(file ${RESOURCES})
# execute_process(
# COMMAND ${CMAKE_COMMAND} -E copy_if_different
# ${CMAKE_CURRENT_SOURCE_DIR}/${file}
# ${EDO_BIN_DIR}/${file}
# )
# endforeach(file)
#file(GLOB SOURCES *.cpp)
set(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR})
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} eo eoutils edoutils ${Boost_LIBRARIES})

156
tutorial/edo/cmaes/main.cpp Executable file
View file

@ -0,0 +1,156 @@
/*
The Evolving Distribution Objects framework (EDO) is a template-based,
ANSI-C++ evolutionary computation library which helps you to write your
own estimation of distribution algorithms.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2010 Thales group
*/
/*
Authors:
Johann Dréo <johann.dreo@thalesgroup.com>
Caner Candan <caner.candan@thalesgroup.com>
*/
#include <paradiseo/eo.h>
//#include <paradiseo/mo.h>
#include <paradiseo/eo/eoEvalFuncCounterBounder.h>
#include <paradiseo/eo/do/make_pop.h>
#include <paradiseo/eo/do/make_run.h>
#include <paradiseo/eo/do/make_continue.h>
#include <paradiseo/eo/do/make_checkpoint.h>
#include <paradiseo/edo.h>
#include "../common/Rosenbrock.h"
#include "../common/Sphere.h"
typedef eoReal<eoMinimizingFitness> RealVec;
typedef edoNormalAdaptive< RealVec > Distrib;
int main(int ac, char** av)
{
eoParser parser(ac, av);
eoState state;
// Letters used by the following declarations:
unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E
unsigned int dim = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', "Problem").value(); // d
double mu = dim / 2;
edoNormalAdaptive<RealVec> distribution(dim);
eoSelect< RealVec >* selector = new eoRankMuSelect< RealVec >( mu );
state.storeFunctor(selector);
edoEstimator< Distrib >* estimator = new edoEstimatorNormalAdaptive<RealVec>( distribution );
state.storeFunctor(estimator);
eoEvalFunc< RealVec >* plainEval = new Rosenbrock< RealVec >();
state.storeFunctor(plainEval);
eoEvalFuncCounterBounder< RealVec > eval(*plainEval, max_eval);
eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5);
state.storeFunctor(gen);
eoInitFixedLength< RealVec >* init = new eoInitFixedLength< RealVec >( dim, *gen );
state.storeFunctor(init);
// (1) Population init and sampler
// Generation of population from do_make_pop (creates parameters, manages persistance and so on...)
// ... and creates the parameters: L P r S
// this first sampler creates a uniform distribution independently from our distribution (it does not use edoUniform).
eoPop< RealVec >& pop = do_make_pop(parser, state, *init);
// (2) First evaluation before starting the research algorithm
apply(eval, pop);
// Prepare bounder class to set bounds of sampling.
// This is used by edoSampler.
edoBounder< RealVec >* bounder =
new edoBounderRng< RealVec >( RealVec(dim, -5), RealVec(dim, 5), *gen); // FIXME do not use hard-coded bounds
state.storeFunctor(bounder);
// Prepare sampler class with a specific distribution
edoSampler< Distrib >* sampler = new edoSamplerNormalAdaptive< RealVec >( *bounder );
state.storeFunctor(sampler);
// stopping criteria
// ... and creates the parameter letters: C E g G s T
eoContinue< RealVec >& eo_continue = do_make_continue(parser, state, eval);
// population output
eoCheckPoint< RealVec >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue);
// keep the best solution found so far in an eoStat
// thus, if the population's best individual fitness decreases during the search, we could
// still keep the best found since the beginning, while avoiding the bias of elitism on the sample
eoBestIndividualStat<RealVec> best_indiv;
pop_continue.add( best_indiv );
// distribution output
edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >();
state.storeFunctor(dummy_continue);
edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue );
state.storeFunctor(distribution_continue);
eoReplacement< RealVec >* replacor = new eoCommaReplacement< RealVec >();
state.storeFunctor(replacor);
// Help + Verbose routines
make_verbose(parser);
make_help(parser);
// Some stuff to display helper when we are using -h option
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
eoPopLoopEval<RealVec> popEval( eval );
// CMA-ES algorithm configuration
edoAlgo< Distrib >* algo = new edoAlgoAdaptive< Distrib >
(distribution, popEval, *selector, *estimator, *sampler, *replacor,
pop_continue, *distribution_continue );
// Use the best solution of the random first pop to start the search
// That is, center the distribution's mean on it.
distribution.mean( pop.best_element() );
// Beginning of the algorithm call
try {
eo::log << eo::progress << "Best solution after random init: " << pop.best_element().fitness() << std::endl;
do_run(*algo, pop);
} catch (eoEvalFuncCounterBounderException& e) {
eo::log << eo::warnings << "warning: " << e.what() << std::endl;
}
// use the stat instead of the pop, to get the best solution of the whole search
std::cout << best_indiv.value() << std::endl;
return 0;
}

View file

@ -0,0 +1,15 @@
PROJECT(common)
SET(RESOURCES
gplot.py
ggobi.py
boxplot_eda_n_edasa.py
)
FOREACH(file ${RESOURCES})
EXECUTE_PROCESS(
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${file}
${EDO_BIN_DIR}/${file}
)
ENDFOREACH(file)

View file

@ -0,0 +1,42 @@
#ifndef _Rosenbrock_h
#define _Rosenbrock_h
#include <paradiseo/eo.h>
#include <paradiseo/eo/es.h>
#include <paradiseo/eo/es/eoRealInitBounded.h>
#include <paradiseo/eo/es/eoRealOp.h>
#include <paradiseo/eo/es/eoEsChromInit.h>
#include <paradiseo/eo/es/eoRealOp.h>
#include <paradiseo/eo/es/make_real.h>
#include <paradiseo/eo/apply.h>
#include <paradiseo/eo/eoProportionalCombinedOp.h>
template < typename EOT >
class Rosenbrock : public eoEvalFunc< EOT >
{
public:
typedef typename EOT::AtomType AtomType;
virtual void operator()( EOT& p )
{
if (!p.invalid())
return;
p.fitness( _evaluate( p ) );
}
private:
AtomType _evaluate( EOT& p )
{
AtomType r = 0.0;
for (unsigned int i = 0; i < p.size() - 1; ++i)
{
r += p[i] * p[i];
}
return r;
}
};
#endif // !_Rosenbrock_h

42
tutorial/edo/common/Sphere.h Executable file
View file

@ -0,0 +1,42 @@
#ifndef _Sphere_h
#define _Sphere_h
#include <paradiseo/eo.h>
#include <paradiseo/eo/es.h>
#include <paradiseo/eo/es/eoRealInitBounded.h>
#include <paradiseo/eo/es/eoRealOp.h>
#include <paradiseo/eo/es/eoEsChromInit.h>
#include <paradiseo/eo/es/eoRealOp.h>
#include <paradiseo/eo/es/make_real.h>
#include <paradiseo/eo/apply.h>
#include <paradiseo/eo/eoProportionalCombinedOp.h>
template < typename EOT >
class Sphere : public eoEvalFunc< EOT >
{
public:
typedef typename EOT::AtomType AtomType;
virtual void operator()( EOT& p )
{
if (!p.invalid())
return;
p.fitness( _evaluate( p ) );
}
private:
AtomType _evaluate( EOT& p )
{
AtomType r = 0.0;
for (unsigned int i = 0; i < p.size() - 1; ++i)
{
r += p[i] * p[i];
}
return r;
}
};
#endif // !_Sphere_h

View file

@ -0,0 +1,36 @@
#!/usr/bin/env python
from pylab import *
#from pprint import pprint
FILE_LOCATIONS = 'EDA_ResPop/list_of_files.txt'
data = []
locations = [ line.split()[0] for line in open( FILE_LOCATIONS ) ]
#pprint( locations )
for cur_file in locations:
fitnesses = [ float(line.split()[0]) for line in open( cur_file ).readlines()[1:-1] ]
data.append( fitnesses[1:] )
#pprint( data )
boxplot( data )
# FILE_LOCATIONS = 'EDASA_ResPop/list_of_files.txt'
# data = []
# locations = [ line.split()[0] for line in open( FILE_LOCATIONS ) ]
# #pprint( locations )
# for cur_file in locations:
# fitnesses = [ float(line.split()[0]) for line in open( cur_file ).readlines()[1:-1] ]
# data.append( fitnesses[1:] )
# #pprint( data )
# boxplot( data )
show()

68
tutorial/edo/common/ggobi.py Executable file
View file

@ -0,0 +1,68 @@
#!/usr/bin/env python
from pprint import *
import sys, os
if __name__ == '__main__':
# parameter phase
if len(sys.argv) < 2:
print 'Usage: %s [FILE]' % sys.argv[0]
sys.exit()
filename = sys.argv[1]
lines = open(filename).readlines()
# formatting phase
try:
results = [ x.split() for x in lines[1:-1] ]
except IOError, e:
print 'Error: %s' % e
sys.exit()
# dimension estimating phase
popsize = int(lines[0].split()[0])
dimsize = int(results[0][1])
# printing phase
print 'popsize: %d' % popsize
print 'dimsize: %d' % dimsize
print
pprint( results )
# cvs converting phase
i = 1
for x in results:
x.insert(0, '"%d"' % i)
i += 1
header = ['""', '"fitness"', '"dimsize"']
for i in range(0, dimsize):
header.append( '"dim%d"' % i )
results.insert(0, header)
# cvs printing phase
file_results = '\n'.join( [ ','.join( x ) for x in results ] )
print
print file_results
try:
open('%s.csv' % filename, 'w').write(file_results + '\n')
except IOError, e:
print 'Error: %s' % e
sys.exit()
# ggobi plotting phase
os.system('ggobi %s.csv' % filename)

399
tutorial/edo/common/gplot.py Executable file
View file

@ -0,0 +1,399 @@
#!/usr/bin/env python
"""plot.py -- Plot EDA-SA results file"""
import os, time, math, tempfile
import numpy
try:
import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils
except ImportError:
# kludge in case Gnuplot hasn't been installed as a module yet:
import __init__
Gnuplot = __init__
import PlotItems
Gnuplot.PlotItems = PlotItems
import funcutils
Gnuplot.funcutils = funcutils
import optparse, logging, sys
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
def logger(level_name, filename='plot.log'):
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
filename=filename, filemode='a'
)
console = logging.StreamHandler()
console.setLevel(LEVELS.get(level_name, logging.NOTSET))
console.setFormatter(logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s'))
logging.getLogger('').addHandler(console)
def parser(parser=optparse.OptionParser()):
parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='warning', help='set a verbose level')
parser.add_option('-f', '--files', help='give some input sample files separated by comma (cf. gen1,gen2,...)', default='')
parser.add_option('-r', '--respop', help='define the population results containing folder', default='./ResPop')
parser.add_option('-o', '--output', help='give an output filename for logging', default='plot.log')
parser.add_option('-d', '--dimension', help='give a dimension size', default=2)
parser.add_option('-m', '--multiplot', action="store_true", help='plot all graphics in one window', dest="multiplot", default=True)
parser.add_option('-p', '--plot', action="store_false", help='plot graphics separetly, one by window', dest="multiplot")
parser.add_option('-w', '--windowid', help='give the window id you want to display, 0 means we display all ones, this option should be combined with -p', default=0)
parser.add_option('-G', '--graphicsdirectory', help='give a directory name for graphics, this option should be combined with -u', default='plot')
parser.add_option('-g', '--graphicsprefixname', help='give a prefix name for graphics, this option should be combined with -u', default='plot')
parser.add_option('-t', '--terminal', action="store_true", help='display graphics on gnuplot windows', dest="terminal", default=True)
parser.add_option('-u', '--png', action="store_false", help='display graphics on png files', dest="terminal")
options, args = parser.parse_args()
logger(options.verbose, options.output)
return options
options = parser()
def wait(str=None, prompt='Press return to show results...\n'):
if str is not None:
print str
raw_input(prompt)
def draw2DRect(min=(0,0), max=(1,1), color='black', state=None, g=None):
if g == None: g = Gnuplot.Gnuplot()
if state != None: state.append(g)
xmin, ymin = min
xmax, ymax = max
cmd = 'set arrow from %s,%s to %s,%s nohead lc rgb "%s"'
g(cmd % (xmin, ymin, xmin, ymax, color))
g(cmd % (xmin, ymax, xmax, ymax, color))
g(cmd % (xmax, ymax, xmax, ymin, color))
g(cmd % (xmax, ymin, xmin, ymin, color))
return g
def draw3DRect(min=(0,0,0), max=(1,1,1), state=None, g=None):
if g == None: g = Gnuplot.Gnuplot()
if state != None: state.append(g)
# TODO
return g
def getSortedFiles(path):
assert path != None
if options.files == '':
filelist = os.listdir(path)
filelist.sort()
else:
filelist = options.files.split(',')
checkFileErrors(path, filelist)
return filelist
def checkFileErrors(path, filelist):
for filename in filelist:
for line in open('%s/%s' % (path, filename)):
if '-nan' in line:
logging.warning("checkFileErrors: %s/%s file contains bad value, it is going to be skipped" % (path, filename))
filelist.remove(filename)
break
def plotXPointYFitness(path, fields='3:1', state=None, g=None):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXPointYFitness'))
if state != None: state.append(g)
g.title('Fitness observation')
g.xlabel('Coordinates')
g.ylabel('Fitness (Quality)')
files=[]
for filename in getSortedFiles(path):
files.append(Gnuplot.File(path + '/' + filename, using=fields,
with_='points',
#title='distribution \'' + filename + '\''
title=""
)
)
if len(files) > 0:
g.plot(*files)
return g
def plotXYPointZFitness(path, fields='4:3:1', state=None, g=None):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYPointZFitness'))
if state != None: state.append(g)
g.title('Fitness observation in 3-D')
g.xlabel('x-axes')
g.ylabel('y-axes')
g.zlabel('Fitness (Quality)')
files=[]
for filename in getSortedFiles(path):
files.append(Gnuplot.File(path + '/' + filename, using=fields,
with_='points',
#title='distribution \'' + filename + '\''
title=""
)
)
if len(files) > 0:
g.splot(*files)
return g
def plotXYPoint(path, fields='3:4', state=None, g=None):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYPoint'))
if state != None: state.append(g)
g.title('Points observation in 2-D')
g.xlabel('x-axes')
g.ylabel('y-axes')
files=[]
for filename in getSortedFiles(path):
files.append(Gnuplot.File(path + '/' + filename, using=fields,
with_='points',
#title='distribution \'' + filename + '\''
title=""
)
)
if len(files) > 0:
g.plot(*files)
return g
def plotXYZPoint(path, fields='3:4:5', state=None, g=None):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYZPoint'))
if state != None: state.append(g)
g.title('Points observation in 3-D')
g.xlabel('x-axes')
g.ylabel('y-axes')
g.zlabel('z-axes')
files=[]
for filename in getSortedFiles(path):
files.append(Gnuplot.File(path + '/' + filename, using=fields,
with_='points',
#title='distribution \'' + filename + '\''
title=""
)
)
if len(files) > 0:
g.splot(*files)
return g
def plotParams(path, field='1', state=None, g=None):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYZPoint'))
if state != None: state.append(g)
g.title('Hyper-volume comparaison through all dimensions')
g.xlabel('Iterations')
g.ylabel('Hyper-volume')
g.plot(Gnuplot.File(path, with_='lines', using=field,
title='multivariate distribution narrowing'))
return g
def plot2DRectFromFiles(path, state=None, g=None, plot=True):
if g == None:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s_%s.png\'' % (options.graphicsprefixname, 'plot2DRectFromFiles'))
if state != None: state.append(g)
g.title('Rectangle drawing observation')
g.xlabel('x-axes')
g.ylabel('y-axes')
x1,x2,y1,y2 = 0,0,0,0
colors = ['red', 'orange', 'blue', 'green', 'gold', 'yellow', 'gray']
#colors = open('rgb.txt', 'r').readlines()
colors_size = len(colors)
i = 0 # for color
for filename in getSortedFiles(path):
line = open(path + '/' + filename, 'r').readline()
fields = line.split(' ')
if not fields[0] == '2':
print 'plot2DRectFromFiles: higher than 2 dimensions not possible to draw'
return
xmin,ymin,xmax,ymax = fields[1:5]
#print xmin,ymin,xmax,ymax
cur_color = colors[i % colors_size]
draw2DRect((xmin,ymin), (xmax,ymax), cur_color, g=g)
g('set obj rect from %s,%s to %s,%s back lw 1.0 fc rgb "%s" fillstyle solid 1.00 border -1'
% (xmin,ymin,xmax,ymax,cur_color)
)
if plot:
if float(xmin) < x1: x1 = float(xmin)
if float(ymin) < y1: y1 = float(ymin)
if float(xmax) > x2: x2 = float(xmax)
if float(ymax) > y2: y2 = float(ymax)
#print x1,y1,x2,y2
i += 1
#print x1,y1,x2,y2
if plot:
g.plot('[%s:%s][%s:%s] -9999 notitle' % (x1, x2, y1, y2))
return g
def main():
gstate = []
n = int(options.dimension)
w = int(options.windowid)
r = options.respop
if not options.terminal:
try:
os.mkdir(options.graphicsdirectory)
except OSError:
pass
if options.multiplot:
g = Gnuplot.Gnuplot()
if not options.terminal:
g('set terminal png')
g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'multiplot'))
g('set parametric')
g('set nokey')
g('set noxtic')
g('set noytic')
g('set noztic')
g('set size 1.0, 1.0')
g('set origin 0.0, 0.0')
g('set multiplot')
g('set size 0.5, 0.5')
g('set origin 0.0, 0.5')
if n >= 1:
plotXPointYFitness(r, state=gstate, g=g)
g('set size 0.5, 0.5')
g('set origin 0.0, 0.0')
if n >= 2:
plotXPointYFitness(r, '4:1', state=gstate, g=g)
g('set size 0.5, 0.5')
g('set origin 0.5, 0.5')
if n >= 2:
plotXYPointZFitness(r, state=gstate, g=g)
g('set size 0.5, 0.5')
g('set origin 0.5, 0.0')
if n >= 2:
plotXYPoint(r, state=gstate, g=g)
elif n >= 3:
plotXYZPoint(r, state=gstate, g=g)
g('set nomultiplot')
else:
if n >= 1 and w in [0, 1]:
plotXPointYFitness(r, state=gstate)
if n >= 2 and w in [0, 2]:
plotXPointYFitness(r, '4:1', state=gstate)
if n >= 2 and w in [0, 3]:
plotXYPointZFitness(r, state=gstate)
if n >= 3 and w in [0, 4]:
plotXYZPoint(r, state=gstate)
if n >= 2 and w in [0, 5]:
plotXYPoint(r, state=gstate)
# if n >= 1:
# plotParams('./ResParams.txt', state=gstate)
# if n >= 2:
# plot2DRectFromFiles('./ResBounds', state=gstate)
# plotXYPoint(r, state=gstate)
# g = plot2DRectFromFiles('./ResBounds', state=gstate, plot=False)
# plotXYPoint(r, g=g)
if options.terminal:
wait(prompt='Press return to end the plot.\n')
# when executed, just run main():
if __name__ == '__main__':
logging.debug('### plotting started ###')
main()
logging.debug('### plotting ended ###')

33
tutorial/edo/eda/CMakeLists.txt Executable file
View file

@ -0,0 +1,33 @@
project(eda)
find_package(Boost 1.33.0)
#include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
#include_directories(${EO_SRC_DIR}/src)
link_directories(${EO_BIN_DIR}/${LIB})
#include_directories(${EDO_SRC_DIR}/src)
link_directories(${EDO_BIN_DIR}/${LIB})
set(RESOURCES
${PROJECT_NAME}.param
)
foreach(FILE ${RESOURCES})
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${FILE}
${EDO_BIN_DIR}/${FILE}
)
endforeach(FILE)
file(GLOB SOURCES *.cpp)
set(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR})
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} eo eoutils edoutils ${Boost_LIBRARIES})

7
tutorial/edo/eda/eda.param Executable file
View file

@ -0,0 +1,7 @@
--rho=0 # -p : <etropolis sample size
--alpha=0 # -a : Temperature dicrease rate
--threshold=0.1 # -t : Temperature threshold stopping criteria
--sample-size=10 # -P : Sample size
--dimension-size=10 # -d : Dimension size
--temperature=100 # -T : Initial temperature
#--verbose # Enable verbose mode

180
tutorial/edo/eda/main.cpp Executable file
View file

@ -0,0 +1,180 @@
/*
The Evolving Distribution Objects framework (EDO) is a template-based,
ANSI-C++ evolutionary computation library which helps you to write your
own estimation of distribution algorithms.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2010 Thales group
*/
/*
Authors:
Johann Dréo <johann.dreo@thalesgroup.com>
Caner Candan <caner.candan@thalesgroup.com>
*/
#include <paradiseo/eo.h>
// #include <mo>
#include <paradiseo/eo/eoEvalFuncCounterBounder.h>
#include <paradiseo/eo/do/make_pop.h>
#include <paradiseo/eo/do/make_run.h>
#include <paradiseo/eo/do/make_continue.h>
#include <paradiseo/eo/do/make_checkpoint.h>
#include <paradiseo/edo.h>
#include "../common/Rosenbrock.h"
#include "../common/Sphere.h"
typedef eoReal<eoMinimizingFitness> EOT;
typedef edoNormalMulti< EOT > Distrib;
int main(int ac, char** av)
{
eoParser parser(ac, av);
// Letters used by the following declarations:
// a d i p t
std::string section("Algorithm parameters");
eoState state;
// Instantiate all needed parameters for EDA algorithm
double selection_rate = parser.createParam((double)0.5, "selection_rate", "Selection Rate", 'R', section).value(); // R
eoSelect< EOT >* selector = new eoDetSelect< EOT >( selection_rate );
state.storeFunctor(selector);
edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >();
state.storeFunctor(estimator);
eoEvalFunc< EOT >* plainEval = new Rosenbrock< EOT >();
state.storeFunctor(plainEval);
unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E
eoEvalFuncCounterBounder< EOT > eval(*plainEval, max_eval);
eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5);
state.storeFunctor(gen);
unsigned int dimension_size = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', section).value(); // d
eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( dimension_size, *gen );
state.storeFunctor(init);
// (1) Population init and sampler
// Generation of population from do_make_pop (creates parameters, manages persistance and so on...)
// ... and creates the parameters: L P r S
// this first sampler creates a uniform distribution independently from our distribution (it does not use edoUniform).
eoPop< EOT >& pop = do_make_pop(parser, state, *init);
// (2) First evaluation before starting the research algorithm
apply(eval, pop);
// Prepare bounder class to set bounds of sampling.
// This is used by edoSampler.
edoBounder< EOT >* bounder =
new edoBounderRng< EOT >( EOT(dimension_size, -5), EOT(dimension_size, 5), *gen); // FIXME do not use hard-coded bounds
state.storeFunctor(bounder);
// Prepare sampler class with a specific distribution
edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder );
state.storeFunctor(sampler);
// stopping criteria
// ... and creates the parameter letters: C E g G s T
eoContinue< EOT >& eo_continue = do_make_continue(parser, state, eval);
// population output
eoCheckPoint< EOT >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue);
// distribution output
edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >();
state.storeFunctor(dummy_continue);
edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue );
state.storeFunctor(distribution_continue);
// eoEPRemplacement causes the using of the current and previous
// sample for sampling.
eoReplacement< EOT >* replacor = new eoEPReplacement< EOT >(pop.size());
state.storeFunctor(replacor);
// Help + Verbose routines
make_verbose(parser);
make_help(parser);
// Some stuff to display helper when we are using -h option
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
// population output (after helper)
//
// FIXME: theses objects are instanciated there in order to avoid a folder
// removing as edoFileSnapshot does within ctor.
edoPopStat< EOT >* popStat = new edoPopStat<EOT>;
state.storeFunctor(popStat);
pop_continue.add(*popStat);
edoFileSnapshot* fileSnapshot = new edoFileSnapshot("EDA_ResPop");
state.storeFunctor(fileSnapshot);
fileSnapshot->add(*popStat);
pop_continue.add(*fileSnapshot);
// distribution output (after helper)
edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >();
state.storeFunctor(distrib_stat);
distribution_continue->add( *distrib_stat );
// eoMonitor* stdout_monitor = new eoStdoutMonitor();
// state.storeFunctor(stdout_monitor);
// stdout_monitor->add(*distrib_stat);
// distribution_continue->add( *stdout_monitor );
eoFileMonitor* file_monitor = new eoFileMonitor("eda_distribution_bounds.txt");
state.storeFunctor(file_monitor);
file_monitor->add(*distrib_stat);
distribution_continue->add( *file_monitor );
eoPopLoopEval<EOT> popEval( eval );
// EDA algorithm configuration
edoAlgo< Distrib >* algo = new edoAlgoStateless< Distrib >
(popEval, *selector, *estimator, *sampler, *replacor,
pop_continue, *distribution_continue );
// Beginning of the algorithm call
try {
do_run(*algo, pop);
} catch (eoEvalFuncCounterBounderException& e) {
eo::log << eo::warnings << "warning: " << e.what() << std::endl;
} catch (std::exception& e) {
eo::log << eo::errors << "error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
return 0;
}

View file

@ -0,0 +1,27 @@
PROJECT(eda_sa)
FIND_PACKAGE(Boost 1.33.0)
#INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})
SET(RESOURCES
${PROJECT_NAME}.param
)
FOREACH(file ${RESOURCES})
EXECUTE_PROCESS(
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${file}
${EDO_BIN_DIR}/${file}
)
ENDFOREACH(file)
FILE(GLOB SOURCES *.cpp)
SET(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR})
ADD_EXECUTABLE(${PROJECT_NAME} ${SOURCES})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} edo edoutils ${EO_LIBRARIES} ${MO_LIBRARIES} ${Boost_LIBRARIES})

View file

@ -0,0 +1,7 @@
--rho=0 # -p : <etropolis sample size
--alpha=0 # -a : Temperature dicrease rate
--threshold=0.1 # -t : Temperature threshold stopping criteria
--sample-size=10 # -P : Sample size
--dimension-size=10 # -d : Dimension size
--temperature=100 # -T : Initial temperature
#--verbose # Enable verbose mode

284
tutorial/edo/eda_sa/main.cpp Executable file
View file

@ -0,0 +1,284 @@
#include <paradiseo/eo.h>
#include <paradiseo/mo.h>
#include <paradiseo/eo/eoEvalFuncCounterBounder.h>
#include <paradiseo/eo/do/make_pop.h>
#include <paradiseo/eo/do/make_run.h>
#include <paradiseo/eo/do/make_continue.h>
#include <paradiseo/eo/do/make_checkpoint.h>
#include <paradiseo/edo.h>
#include "../common/Rosenbrock.h"
#include "../common/Sphere.h"
typedef eoReal<eoMinimizingFitness> EOT;
typedef edoNormalMulti< EOT > Distrib;
int main(int ac, char** av)
{
eoParser parser(ac, av);
// Letters used by the following declarations:
// a d i p t
std::string section("Algorithm parameters");
// FIXME: default value to check
double initial_temperature = parser.createParam((double)10e5, "temperature", "Initial temperature", 'i', section).value(); // i
eoState state;
//-----------------------------------------------------------------------------
// Instantiate all needed parameters for EDASA algorithm
//-----------------------------------------------------------------------------
double selection_rate = parser.createParam((double)0.5, "selection_rate", "Selection Rate", 'R', section).value(); // R
eoSelect< EOT >* selector = new eoDetSelect< EOT >( selection_rate );
state.storeFunctor(selector);
edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >();
state.storeFunctor(estimator);
eoSelectOne< EOT >* selectone = new eoDetTournamentSelect< EOT >( 2 );
state.storeFunctor(selectone);
edoModifierMass< Distrib >* modifier = new edoNormalMultiCenter< EOT >();
state.storeFunctor(modifier);
eoEvalFunc< EOT >* plainEval = new Rosenbrock< EOT >();
state.storeFunctor(plainEval);
unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E
eoEvalFuncCounterBounder< EOT > eval(*plainEval, max_eval);
eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5);
state.storeFunctor(gen);
unsigned int dimension_size = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', section).value(); // d
eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( dimension_size, *gen );
state.storeFunctor(init);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// (1) Population init and sampler
//-----------------------------------------------------------------------------
// Generation of population from do_make_pop (creates parameters, manages persistance and so on...)
// ... and creates the parameters: L P r S
// this first sampler creates a uniform distribution independently from our distribution (it does not use doUniform).
eoPop< EOT >& pop = do_make_pop(parser, state, *init);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// (2) First evaluation before starting the research algorithm
//-----------------------------------------------------------------------------
apply(eval, pop);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Prepare bounder class to set bounds of sampling.
// This is used by doSampler.
//-----------------------------------------------------------------------------
edoBounder< EOT >* bounder = new edoBounderRng< EOT >(EOT(pop[0].size(), -5),
EOT(pop[0].size(), 5),
*gen);
state.storeFunctor(bounder);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Prepare sampler class with a specific distribution
//-----------------------------------------------------------------------------
edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder );
state.storeFunctor(sampler);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Metropolis sample parameters
//-----------------------------------------------------------------------------
unsigned int popSize = parser.getORcreateParam((unsigned int)20, "popSize", "Population Size", 'P', "Evolution Engine").value();
moContinuator< moDummyNeighbor<EOT> >* sa_continue = new moIterContinuator< moDummyNeighbor<EOT> >( popSize );
state.storeFunctor(sa_continue);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// SA parameters
//-----------------------------------------------------------------------------
double threshold_temperature = parser.createParam((double)0.1, "threshold", "Minimal temperature at which stop", 't', section).value(); // t
double alpha = parser.createParam((double)0.1, "alpha", "Temperature decrease rate", 'a', section).value(); // a
moCoolingSchedule<EOT>* cooling_schedule = new moSimpleCoolingSchedule<EOT>(initial_temperature, alpha, 0, threshold_temperature);
state.storeFunctor(cooling_schedule);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// stopping criteria
// ... and creates the parameter letters: C E g G s T
//-----------------------------------------------------------------------------
eoContinue< EOT >& eo_continue = do_make_continue(parser, state, eval);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// population output
//-----------------------------------------------------------------------------
eoCheckPoint< EOT >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// distribution output
//-----------------------------------------------------------------------------
edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >();
state.storeFunctor(dummy_continue);
edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue );
state.storeFunctor(distribution_continue);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// eoEPRemplacement causes the using of the current and previous
// sample for sampling.
//-----------------------------------------------------------------------------
eoReplacement< EOT >* replacor = new eoEPReplacement< EOT >(pop.size());
// Below, use eoGenerationalReplacement to sample only on the current sample
//eoReplacement< EOT >* replacor = new eoGenerationalReplacement< EOT >(); // FIXME: to define the size
state.storeFunctor(replacor);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Some stuff to display helper when we are using -h option
//-----------------------------------------------------------------------------
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
// Help + Verbose routines
make_verbose(parser);
make_help(parser);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// population output (after helper)
//
// FIXME: theses objects are instanciate there in order to avoid a folder
// removing as edoFileSnapshot does within ctor.
//-----------------------------------------------------------------------------
edoPopStat< EOT >* popStat = new edoPopStat<EOT>;
state.storeFunctor(popStat);
pop_continue.add(*popStat);
edoFileSnapshot* fileSnapshot = new edoFileSnapshot("EDASA_ResPop");
state.storeFunctor(fileSnapshot);
fileSnapshot->add(*popStat);
pop_continue.add(*fileSnapshot);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// distribution output (after helper)
//-----------------------------------------------------------------------------
edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >();
state.storeFunctor(distrib_stat);
distribution_continue->add( *distrib_stat );
// eoMonitor* stdout_monitor = new eoStdoutMonitor();
// state.storeFunctor(stdout_monitor);
// stdout_monitor->add(*distrib_stat);
// distribution_continue->add( *stdout_monitor );
eoFileMonitor* file_monitor = new eoFileMonitor("eda_sa_distribution_bounds.txt");
state.storeFunctor(file_monitor);
file_monitor->add(*distrib_stat);
distribution_continue->add( *file_monitor );
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// EDASA algorithm configuration
//-----------------------------------------------------------------------------
edoAlgo< Distrib >* algo = new edoEDASA< Distrib >
(*selector, *estimator, *selectone, *modifier, *sampler,
pop_continue, *distribution_continue,
eval, *sa_continue, *cooling_schedule,
initial_temperature, *replacor);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Beginning of the algorithm call
//-----------------------------------------------------------------------------
try
{
do_run(*algo, pop);
}
catch (eoEvalFuncCounterBounderException& e)
{
eo::log << eo::warnings << "warning: " << e.what() << std::endl;
}
catch (std::exception& e)
{
eo::log << eo::errors << "error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
//-----------------------------------------------------------------------------
return 0;
}

14
tutorial/eo/CMakeLists.txt Executable file
View file

@ -0,0 +1,14 @@
######################################################################################
### 1) Where must cmake go now ?
######################################################################################
ADD_SUBDIRECTORY(Lesson1)
ADD_SUBDIRECTORY(Lesson2)
ADD_SUBDIRECTORY(Lesson3)
ADD_SUBDIRECTORY(Lesson4)
ADD_SUBDIRECTORY(Lesson5)
ADD_SUBDIRECTORY(Lesson6)
ADD_SUBDIRECTORY(app) # deprecated
######################################################################################

502
tutorial/eo/LICENSE Executable file
View file

@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 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.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. 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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; 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.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -0,0 +1,64 @@
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${EO_SRC_DIR}/src/ga)
#include_directories(${EO_SRC_DIR}/src/utils)
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
# no matter what is the OS, hopefully
add_executable(FirstBitGA FirstBitGA.cpp)
add_executable(FirstRealGA FirstRealGA.cpp)
add_executable(exercise1.3 exercise1.3.cpp)
add_dependencies(FirstBitGA ga eo eoutils)
add_dependencies(FirstRealGA ga eo eoutils)
add_dependencies(exercise1.3 ga eo eoutils)
######################################################################################
### 4) Optionnal
######################################################################################
set(FIRSTBITGA_VERSION ${GLOBAL_VERSION})
set_target_properties(FirstBitGA PROPERTIES VERSION "${FIRSTBITGA_VERSION}")
set(FIRSTREALGA_VERSION ${GLOBAL_VERSION})
set_target_properties(FirstRealGA PROPERTIES VERSION "${FIRSTREALGA_VERSION}")
set(EXERCICE13_VERSION ${GLOBAL_VERSION})
set_target_properties(exercise1.3 PROPERTIES VERSION "${EXERCICE13_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(FirstBitGA ga eo eoutils)
target_link_libraries(FirstRealGA ga eo eoutils)
target_link_libraries(exercise1.3 ga eo eoutils)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS FirstBitGA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson1 COMPONENT examples)
install(TARGETS FirstRealGA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson1 COMPONENT examples)
install(TARGETS exercise1.3 RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson1 COMPONENT examples)
######################################################################################

View file

@ -0,0 +1,167 @@
//-----------------------------------------------------------------------------
// FirstBitGA.cpp
//-----------------------------------------------------------------------------
//*
// An instance of a VERY simple Bitstring Genetic Algorithm
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <iostream>
#include <paradiseo/eo.h>
#include <paradiseo/eo/ga.h>
// Use functions from namespace std
using namespace std;
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your individuals
typedef eoBit<double> Indi; // A bitstring with fitness double
// EVAL
//-----------------------------------------------------------------------------
// a simple fitness function that computes the number of ones of a bitstring
// @param _indi A biststring individual
double binary_value(const Indi & _indi)
{
double sum = 0;
for (unsigned i = 0; i < _indi.size(); i++)
sum += _indi[i];
return sum;
}
// GENERAL
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
// PARAMETRES
// all parameters are hard-coded!
const unsigned int SEED = 42; // seed for random number generator
const unsigned int T_SIZE = 3; // size for tournament selection
const unsigned int VEC_SIZE = 16; // Number of bits in genotypes
const unsigned int POP_SIZE = 100; // Size of population
const unsigned int MAX_GEN = 400; // Maximum number of generation before STOP
const float CROSS_RATE = 0.8; // Crossover rate
const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation
const float MUT_RATE = 1.0; // mutation rate
// GENERAL
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
eoEvalFuncPtr<Indi> eval( binary_value );
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// declare the population
eoPop<Indi> pop;
// fill it!
for (unsigned int igeno=0; igeno<POP_SIZE; igeno++)
{
Indi v; // void individual, to be filled
for (unsigned ivar=0; ivar<VEC_SIZE; ivar++)
{
bool r = rng.flip(); // new value, random in {0,1}
v.push_back(r); // append that random value to v
}
eval(v); // evaluate it
pop.push_back(v); // and put it in the population
}
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// shuffle - this is a test
pop.shuffle();
// Print (sorted) intial population (raw printout)
cout << "Shuffled Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> select(T_SIZE); // T_SIZE in [2,POP_SIZE]
// REPLACE
// The simple GA evolution engine uses generational replacement
// so no replacement procedure is needed
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// 1-point crossover for bitstring
eo1PtBitXover<Indi> xover;
// MUTATION
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutation(P_MUT_PER_BIT);
// STOP
// CHECKPOINT
//////////////////////////////////////
// termination condition
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> continuator(MAX_GEN);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// standard Generational GA requires as parameters
// selection, evaluation, crossover and mutation, stopping criterion
eoSGA<Indi> gga(select, xover, CROSS_RATE, mutation, MUT_RATE,
eval, continuator);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,162 @@
//-----------------------------------------------------------------------------
// FirstRealGA.cpp
//-----------------------------------------------------------------------------
//*
// An instance of a VERY simple Real-coded Genetic Algorithm
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <paradiseo/eo.h>
#include <paradiseo/eo/es.h>
// Use functions from namespace std
using namespace std;
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your individuals
typedef eoReal<double> Indi;
// EVAL
//-----------------------------------------------------------------------------
// a simple fitness function that computes the euclidian norm of a real vector
// @param _indi A real-valued individual
double real_value(const Indi & _indi)
{
double sum = 0;
for (unsigned i = 0; i < _indi.size(); i++)
sum += _indi[i]*_indi[i];
return (-sum); // maximizing only
}
// GENERAL
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
// PARAMETRES
// all parameters are hard-coded!
const unsigned int SEED = 42; // seed for random number generator
const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes
const unsigned int POP_SIZE = 20; // Size of population
const unsigned int T_SIZE = 3; // size for tournament selection
const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
const float CROSS_RATE = 0.8; // Crossover rate
const double EPSILON = 0.01; // range for real uniform mutation
const float MUT_RATE = 0.5; // mutation rate
// GENERAL
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
eoEvalFuncPtr<Indi> eval( real_value );
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// declare the population
eoPop<Indi> pop;
// fill it!
for (unsigned int igeno=0; igeno<POP_SIZE; igeno++)
{
Indi v; // void individual, to be filled
for (unsigned ivar=0; ivar<VEC_SIZE; ivar++)
{
double r = 2*rng.uniform() - 1; // new value, random in [-1,1)
v.push_back(r); // append that random value to v
}
eval(v); // evaluate it
pop.push_back(v); // and put it in the population
}
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> select(T_SIZE); // T_SIZE in [2,POP_SIZE]
// REPLACE
// eoSGA uses generational replacement by default
// so no replacement procedure has to be given
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// offspring(i) is a linear combination of parent(i)
eoSegmentCrossover<Indi> xover;
// MUTATION
// offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
eoUniformMutation<Indi> mutation(EPSILON);
// STOP
// CHECKPOINT
//////////////////////////////////////
// termination condition
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> continuator(MAX_GEN);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// standard Generational GA requires
// selection, evaluation, crossover and mutation, stopping criterion
eoSGA<Indi> gga(select, xover, CROSS_RATE, mutation, MUT_RATE,
eval, continuator);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,25 @@
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp
firstGA = FirstRealGA FirstBitGA
ALL = $(firstGA) exercise1.3
lesson1 : $(firstGA)
all : $(ALL)
clean :
@/bin/rm $(ALL) *.o *~

View file

@ -0,0 +1,162 @@
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
//-----------------------------------------------------------------------------
// FirstBitGA.cpp
//-----------------------------------------------------------------------------
//*
// An instance of a VERY simple Bitstring Genetic Algorithm
//
//-----------------------------------------------------------------------------
// standard includes
#include <iostream>
#include <stdexcept>
// the general include for eo
#include <paradiseo/eo.h>
//-----------------------------------------------------------------------------
// Include the corresponding file
#include <paradiseo/eo/ga.h> // bitstring representation & operators
// define your individuals
typedef eoBit<double> Indi; // A bitstring with fitness double
using namespace std;
//-----------------------------------------------------------------------------
/** a simple fitness function that computes the number of ones of a bitstring
@param _indi A biststring individual
*/
double binary_value(const Indi & _indi)
{
double sum = 0;
for (unsigned i = 0; i < _indi.size(); i++)
sum += _indi[i];
return sum;
}
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
const unsigned int SEED = 42; // seed for random number generator
const unsigned int VEC_SIZE = 8; // Number of bits in genotypes
const unsigned int POP_SIZE = 20; // Size of population
const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
const float CROSS_RATE = 0.8; // Crossover rate
const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation
const float MUT_RATE = 1.0; // mutation rate
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
eoEvalFuncPtr<Indi> eval( binary_value );
////////////////////////////////
// Initilisation of population
////////////////////////////////
// declare the population
eoPop<Indi> pop;
// fill it!
for (unsigned int igeno=0; igeno<POP_SIZE; igeno++)
{
Indi v; // void individual, to be filled
for (unsigned ivar=0; ivar<VEC_SIZE; ivar++)
{
bool r = rng.flip(); // new value, random in {0,1}
v.push_back(r); // append that random value to v
}
eval(v); // evaluate it
pop.push_back(v); // and put it in the population
}
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// solution solution solution: uncomment one of the following,
// comment out the eoDetTournament lines
// The well-known roulette
// eoProportionalSelect<Indi> select;
// could also use stochastic binary tournament selection
//
// const double RATE = 0.75;
// eoStochTournamentSelect<Indi> select(RATE); // RATE in ]0.5,1]
// The robust tournament selection
const unsigned int T_SIZE = 3; // size for tournament selection
eoDetTournamentSelect<Indi> select(T_SIZE); // T_SIZE in [2,POP_SIZE]
// and of course the random selection
// eoRandomSelect<Indi> select;
// The simple GA evolution engine uses generational replacement
// so no replacement procedure is needed
//////////////////////////////////////
// termination condition
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> continuator(MAX_GEN);
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutation(P_MUT_PER_BIT);
// 1-point mutation for bitstring
eo1PtBitXover<Indi> xover;
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// standard Generational GA requires as parameters
// selection, evaluation, crossover and mutation, stopping criterion
eoSGA<Indi> gga(select, xover, CROSS_RATE, mutation, MUT_RATE,
eval, continuator);
// Apply algo to pop - that's it!
gga(pop);
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,60 @@
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${EO_SRC_DIR}/src/ga)
#include_directories(${EO_SRC_DIR}/src/utils)
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
# no matter what is the OS, hopefully
add_executable(FirstBitEA FirstBitEA.cpp)
add_executable(FirstRealEA FirstRealEA.cpp)
add_executable(exercise2.3 exercise2.3.cpp)
######################################################################################
### 4) Optionnal
######################################################################################
set(FIRSTBITEA_VERSION ${GLOBAL_VERSION})
set_target_properties(FirstBitEA PROPERTIES VERSION "${FIRSTBITEA_VERSION}")
set(FIRSTREALEA_VERSION ${GLOBAL_VERSION})
set_target_properties(FirstRealEA PROPERTIES VERSION "${FIRSTREALEA_VERSION}")
set(EXERCICE23_VERSION ${GLOBAL_VERSION})
set_target_properties(exercise2.3 PROPERTIES VERSION "${EXERCICE23_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(FirstBitEA ga eo eoutils)
target_link_libraries(FirstRealEA ga eo eoutils)
target_link_libraries(exercise2.3 ga eo eoutils)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS FirstBitEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson2 COMPONENT examples)
install(TARGETS FirstRealEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson2 COMPONENT examples)
install(TARGETS exercise2.3 RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson2 COMPONENT examples)
######################################################################################

View file

@ -0,0 +1,193 @@
//-----------------------------------------------------------------------------
// FirstBitEA.cpp
//-----------------------------------------------------------------------------
//*
// Still an instance of a VERY simple Bitstring Genetic Algorithm
// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <stdexcept> // runtime_error
#include <iostream> // cout
// the general include for eo
#include <paradiseo/eo.h>
#include <paradiseo/eo/ga.h>
// Use functions from namespace std
using namespace std;
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your individuals
typedef eoBit<double> Indi; // A bitstring with fitness double
// EVALFUNC
//-----------------------------------------------------------------------------
// a simple fitness function that computes the number of ones of a bitstring
// Now in a separate file, and declared as binary_value(const vector<bool> &)
#include "binary_value.h"
// GENERAL
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
// PARAMETRES
const unsigned int SEED = 42; // seed for random number generator
const unsigned int T_SIZE = 3; // size for tournament selection
const unsigned int VEC_SIZE = 8; // Number of bits in genotypes
const unsigned int POP_SIZE = 20; // Size of population
const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
const unsigned int MIN_GEN = 10; // Minimum number of generation before ...
const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent
const double P_CROSS = 0.8; // Crossover probability
const double P_MUT = 1.0; // mutation probability
const double P_MUT_PER_BIT = 0.01; // internal probability for bit-flip mutation
// some parameters for chosing among different operators
const double onePointRate = 0.5; // rate for 1-pt Xover
const double twoPointsRate = 0.5; // rate for 2-pt Xover
const double URate = 0.5; // rate for Uniform Xover
const double bitFlipRate = 0.5; // rate for bit-flip mutation
const double oneBitRate = 0.5; // rate for one-bit mutation
// GENERAL
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
// you need to give the full description of the function
eoEvalFuncPtr<Indi, double, const vector<bool>& > eval( binary_value );
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// based on boolean_generator class (see utils/eoRndGenerators.h)
eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(VEC_SIZE, uGen);
// Initialization of the population
eoPop<Indi> pop(POP_SIZE, random);
// and evaluate it in one loop
apply<Indi>(eval, pop); // STL syntax
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(T_SIZE); // T_SIZE in [2,POP_SIZE]
// is now encapsulated in a eoSelectPerc (entage)
eoSelectPerc<Indi> select(selectOne);// by default rate==1
// REPLACE
// And we now have the full slection/replacement - though with
// no replacement (== generational replacement) at the moment :-)
eoGenerationalReplacement<Indi> replace;
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// 1-point crossover for bitstring
eo1PtBitXover<Indi> xover1;
// uniform crossover for bitstring
eoUBitXover<Indi> xoverU;
// 2-pots xover
eoNPtsBitXover<Indi> xover2(2);
// Combine them with relative rates
eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
xover.add(xoverU, URate);
xover.add(xover2, twoPointsRate);
// MUTATION
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(P_MUT_PER_BIT);
// mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, P_CROSS, mutation, P_MUT);
// STOP
// CHECKPOINT
//////////////////////////////////////
// termination conditions: use more than one
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> genCont(MAX_GEN);
// do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement
eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN);
// stop when fitness reaches a target (here VEC_SIZE)
eoFitContinue<Indi> fitCont(VEC_SIZE);
// do stop when one of the above says so
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// selection, transformation, eval, replacement, and stopping criterion
eoEasyEA<Indi> gga(continuator, eval, select, transform, replace);
// Apply algo to pop - that's it!
cout << "\n Here we go\n\n";
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,192 @@
//-----------------------------------------------------------------------------
// FirstRealEA.cpp
//-----------------------------------------------------------------------------
//*
// Still an instance of a VERY simple Real-coded Genetic Algorithm
// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <stdexcept> // runtime_error
#include <iostream> // cout
// the general include for eo
#include <paradiseo/eo.h>
#include <paradiseo/eo/es.h>
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your individuals
typedef eoReal<double> Indi;
// Use functions from namespace std
using namespace std;
// EVALFUNC
//-----------------------------------------------------------------------------
// a simple fitness function that computes the euclidian norm of a real vector
// Now in a separate file, and declared as binary_value(const vector<bool> &)
#include "real_value.h"
// GENERAL
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
// PARAMETRES
const unsigned int SEED = 42; // seed for random number generator
const unsigned int T_SIZE = 3; // size for tournament selection
const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes
const unsigned int POP_SIZE = 20; // Size of population
const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
const unsigned int MIN_GEN = 10; // Minimum number of generation before ...
const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent
const float P_CROSS = 0.8; // Crossover probability
const float P_MUT = 0.5; // mutation probability
const double EPSILON = 0.01; // range for real uniform mutation
double SIGMA = 0.3; // std dev. for normal mutation
// some parameters for chosing among different operators
const double hypercubeRate = 0.5; // relative weight for hypercube Xover
const double segmentRate = 0.5; // relative weight for segment Xover
const double uniformMutRate = 0.5; // relative weight for uniform mutation
const double detMutRate = 0.5; // relative weight for det-uniform mutation
const double normalMutRate = 0.5; // relative weight for normal mutation
// GENERAL
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
// you need to give the full description of the function
eoEvalFuncPtr<Indi, double, const vector<double>& > eval( real_value );
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// based on a uniform generator
eoUniformGenerator<double> uGen(-1.0, 1.0);
eoInitFixedLength<Indi> random(VEC_SIZE, uGen);
// Initialization of the population
eoPop<Indi> pop(POP_SIZE, random);
// and evaluate it in one loop
apply<Indi>(eval, pop); // STL syntax
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(T_SIZE);
// is now encapsulated in a eoSelectPerc (entage)
eoSelectPerc<Indi> select(selectOne);// by default rate==1
// REPLACE
// And we now have the full slection/replacement - though with
// no replacement (== generational replacement) at the moment :-)
eoGenerationalReplacement<Indi> replace;
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// uniform chooce on segment made by the parents
eoSegmentCrossover<Indi> xoverS;
// uniform choice in hypercube built by the parents
eoHypercubeCrossover<Indi> xoverA;
// Combine them with relative weights
eoPropCombinedQuadOp<Indi> xover(xoverS, segmentRate);
xover.add(xoverA, hypercubeRate);
// MUTATION
// offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
eoUniformMutation<Indi> mutationU(EPSILON);
// k (=1) coordinates of parents are uniformly modified
eoDetUniformMutation<Indi> mutationD(EPSILON);
// all coordinates of parents are normally modified (stDev SIGMA)
eoNormalMutation<Indi> mutationN(SIGMA);
// Combine them with relative weights
eoPropCombinedMonOp<Indi> mutation(mutationU, uniformMutRate);
mutation.add(mutationD, detMutRate);
mutation.add(mutationN, normalMutRate, true);
// STOP
// CHECKPOINT
//////////////////////////////////////
// termination conditions: use more than one
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> genCont(MAX_GEN);
// do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement
eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN);
// stop when fitness reaches a target (here VEC_SIZE)
eoFitContinue<Indi> fitCont(0);
// do stop when one of the above says so
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, P_CROSS, mutation, P_MUT);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// selection, transformation, eval, replacement, and stopping criterion
eoEasyEA<Indi> gga(continuator, eval, select, transform, replace);
// Apply algo to pop - that's it!
cout << "\n Here we go\n\n";
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,34 @@
### This Makefile is part of the tutorial of the EO library
# Unlike other Makefiles in EO, it is not using the automake/autoconf
# so that it stays easy to understant (you are in the tutorial, remember!)
# MS, Oct. 2002
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp
firstEA = FirstRealEA FirstBitEA
ALL = $(firstEA) exercise2.3
lesson2 : $(firstEA)
all : $(ALL)
clean :
@/bin/rm $(ALL) *.o *~
FirstRealEA : real_value.h
FirstBitEA : binary_value.h

View file

@ -0,0 +1,16 @@
#include <paradiseo/eo.h>
//-----------------------------------------------------------------------------
/** Just a simple function that takes binary value of a chromosome and sets
the fitnes.
@param _chrom A binary chromosome
*/
// INIT
double binary_value(const std::vector<bool>& _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum;
}

View file

@ -0,0 +1,197 @@
//-----------------------------------------------------------------------------
// FirstBitEA.cpp
//-----------------------------------------------------------------------------
//*
// Still an instance of a VERY simple Bitstring Genetic Algorithm
// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <stdexcept> // runtime_error
#include <iostream> // cout
// the general include for eo
#include <paradiseo/eo.h>
// REPRESENTATION
//-----------------------------------------------------------------------------
// Include the corresponding file
#include <paradiseo/eo/ga.h> // bitstring representation & operators
// define your individuals
typedef eoBit<double> Indi; // A bitstring with fitness double
// EVAL
//-----------------------------------------------------------------------------
// a simple fitness function that computes the number of ones of a bitstring
// Now in a separate file, and declared as binary_value(const vector<bool> &)
#include "binary_value.h"
// GENERAL
//-----------------------------------------------------------------------------
using namespace std;
void main_function(int argc, char **argv)
{
// PARAMETRES
const unsigned int SEED = 42; // seed for random number generator
const unsigned int T_SIZE = 3; // size for tournament selection
const unsigned int VEC_SIZE = 20; // Number of bits in genotypes
const unsigned int POP_SIZE = 20; // Size of population
const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
const unsigned int MIN_GEN = 10; // Minimum number of generation before ...
const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent
const double P_CROSS = 0.8; // Crossover probability
const double P_MUT = 1.0; // mutation probability
const double P_MUT_PER_BIT = 0.01; // internal probability for bit-flip mutation
// some parameters for chosing among different operators
const double onePointRate = 0.5; // rate for 1-pt Xover
const double twoPointsRate = 0.5; // rate for 2-pt Xover
const double URate = 0.5; // rate for Uniform Xover
const double bitFlipRate = 0.5; // rate for bit-flip mutation
const double oneBitRate = 0.5; // rate for one-bit mutation
// GENERAL
//////////////////////////
// Random seed
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
// you need to give the full description of the function
eoEvalFuncPtr<Indi, double, const vector<bool>& > eval( binary_value );
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(VEC_SIZE, uGen);
// Initialization of the population
eoPop<Indi> pop(POP_SIZE, random);
// and evaluate it in one loop
apply<Indi>(eval, pop); // STL syntax
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(T_SIZE); // T_SIZE in [2,POP_SIZE]
// solution solution solution solution solution solution solution
// modify the nb offspring / rate in the constructor. 2 ways:
// second arg treated as integer
eoSelectMany<Indi> select(selectOne,2, eo_is_an_integer);
// second arg treated as a rate (default behavior)
// eoSelectMany<Indi> select(selectOne,0.1);
// REPLACE
// solution solution solution solution solution solution solution
// eoCommaReplacement keeps the best among offspring
// eoPlusReplacement keeps the best among parents + offspring
// eoCommaReplacement<Indi> replace;
eoPlusReplacement<Indi> replace;
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// 1-point crossover for bitstring
eo1PtBitXover<Indi> xover1;
// uniform crossover for bitstring
eoUBitXover<Indi> xoverU;
// 2-pots xover
eoNPtsBitXover<Indi> xover2(2);
// Combine them with relative rates
eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
xover.add(xoverU, URate);
xover.add(xover2, twoPointsRate);
// MUTATION
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(P_MUT_PER_BIT);
// mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, P_CROSS, mutation, P_MUT);
// STOP
// CHECKPOINT
//////////////////////////////////////
// termination conditions: use more than one
/////////////////////////////////////
// stop after MAX_GEN generations
eoGenContinue<Indi> genCont(MAX_GEN);
// do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement
eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN);
// stop when fitness reaches a target (here VEC_SIZE)
eoFitContinue<Indi> fitCont(VEC_SIZE);
// do stop when one of the above says so
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// selection, transformation, eval, replacement, and stopping criterion
eoEasyEA<Indi> gga(continuator, eval, select, transform, replace);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,17 @@
#include <vector>
//-----------------------------------------------------------------------------
/** Just a simple function that takes an vector<double> and sets the fitnes
to the sphere function. Please use doubles not float!!!
@param _ind A floatingpoint vector
*/
// INIT
double real_value(const std::vector<double>& _ind)
{
double sum = 0;
for (unsigned i = 0; i < _ind.size(); i++)
{
sum += _ind[i] * _ind[i];
}
return -sum;
}

View file

@ -0,0 +1,64 @@
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${EO_SRC_DIR}/src/ga)
#include_directories(${EO_SRC_DIR}/src/utils)
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
# no matter what is the OS, hopefully
add_executable(SecondBitEA SecondBitEA.cpp)
add_executable(SecondRealEA SecondRealEA.cpp)
add_executable(exercise3.1 exercise3.1.cpp)
add_dependencies(SecondBitEA ga eoutils eo)
add_dependencies(SecondRealEA ga eoutils eo)
add_dependencies(exercise3.1 ga eoutils eo)
######################################################################################
### 4) Optionnal
######################################################################################
set(SECONDBITEA_VERSION ${GLOBAL_VERSION})
set_target_properties(SecondBitEA PROPERTIES VERSION "${SECONDBITEA_VERSION}")
set(SECONDREALEA_VERSION ${GLOBAL_VERSION})
set_target_properties(SecondRealEA PROPERTIES VERSION "${SECONDREALEA_VERSION}")
set(EXERCICE31_VERSION ${GLOBAL_VERSION})
set_target_properties(exercise3.1 PROPERTIES VERSION "${EXERCICE31_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(SecondBitEA ga eoutils eo)
target_link_libraries(SecondRealEA ga eoutils eo)
target_link_libraries(exercise3.1 ga eoutils eo)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS SecondBitEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson3 COMPONENT examples)
install(TARGETS SecondRealEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson3 COMPONENT examples)
install(TARGETS exercise3.1 RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson3 COMPONENT examples)
######################################################################################

View file

@ -0,0 +1,33 @@
### This Makefile is part of the tutorial of the EO library
# Unlike other Makefiles in EO, it is not using the automake/autoconf
# so that it stays easy to understant (you are in the tutorial, remember!)
# MS, Oct. 2002
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp
secondEA = SecondBitEA SecondRealEA
ALL = $(secondEA) exercise3.1
lesson3 : $(secondEA)
all : $(ALL)
SecondBitEA : binary_value.h
SecondRealEA : real_value.h
clean :
@/bin/rm $(ALL) *.o *.sav *.xg *.status *~

View file

@ -0,0 +1,348 @@
//-----------------------------------------------------------------------------
// SecondGA.cpp
//-----------------------------------------------------------------------------
//*
// Same code than FirstBitEA as far as Evolutionary Computation is concerned
// but now you learn to enter the parameters in a more flexible way
// and to twidle the output to your preferences!
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <fstream>
#include <iostream> // cout
#include <stdexcept> // runtime_error
// the general include for eo
#include <paradiseo/eo.h>
#include <paradiseo/eo/ga.h>
// Use functions from namespace std
using namespace std;
// EVAL
#include "binary_value.h"
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your genotype and fitness types
typedef eoBit<double> Indi;
// the main_function: nothing changed(!), except variable initialization
void main_function(int argc, char **argv)
{
// PARAMETRES
//-----------------------------------------------------------------------------
// instead of having all values of useful parameters as constants, read them:
// either on the command line (--option=value or -o=value)
// or in a parameter file (same syntax, order independent,
// # = usual comment character
// or in the environment (TODO)
// First define a parser from the command-line arguments
eoParser parser(argc, argv);
// For each parameter, define Parameter, read it through the parser,
// and assign the value to the variable
eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam );
unsigned seed = seedParam.value();
// description of genotype
eoValueParam<unsigned int> vecSizeParam(8, "vecSize", "Genotype size",'V');
parser.processParam( vecSizeParam, "Representation" );
unsigned vecSize = vecSizeParam.value();
// parameters for evolution engine
eoValueParam<unsigned int> popSizeParam(10, "popSize", "Population size",'P');
parser.processParam( popSizeParam, "Evolution engine" );
unsigned popSize = popSizeParam.value();
eoValueParam<unsigned int> tSizeParam(10, "tSize", "Tournament size",'T');
parser.processParam( tSizeParam, "Evolution Engine" );
unsigned tSize = tSizeParam.value();
// init and stop
eoValueParam<string> loadNameParam("", "Load","A save file to restart from",'L');
parser.processParam( loadNameParam, "Persistence" );
string loadName = loadNameParam.value();
eoValueParam<unsigned int> maxGenParam(100, "maxGen", "Maximum number of generations",'G');
parser.processParam( maxGenParam, "Stopping criterion" );
unsigned maxGen = maxGenParam.value();
eoValueParam<unsigned int> minGenParam(100, "minGen", "Minimum number of generations",'g');
parser.processParam( minGenParam, "Stopping criterion" );
unsigned minGen = minGenParam.value();
eoValueParam<unsigned int> steadyGenParam(100, "steadyGen", "Number of generations with no improvement",'s');
parser.processParam( steadyGenParam, "Stopping criterion" );
unsigned steadyGen = steadyGenParam.value();
// operators probabilities at the algorithm level
eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C');
parser.processParam( pCrossParam, "Genetic Operators" );
double pCross = pCrossParam.value();
eoValueParam<double> pMutParam(0.1, "pMut", "Probability of Mutation", 'M');
parser.processParam( pMutParam, "Genetic Operators" );
double pMut = pMutParam.value();
// relative rates for crossovers
eoValueParam<double> onePointRateParam(1, "onePointRate", "Relative rate for one point crossover", '1');
parser.processParam( onePointRateParam, "Genetic Operators" );
double onePointRate = onePointRateParam.value();
eoValueParam<double> twoPointsRateParam(1, "twoPointRate", "Relative rate for two point crossover", '2');
parser.processParam( twoPointsRateParam, "Genetic Operators" );
double twoPointsRate = twoPointsRateParam.value();
eoValueParam<double> uRateParam(2, "uRate", "Relative rate for uniform crossover", 'U');
parser.processParam( uRateParam, "Genetic Operators" );
double URate = uRateParam.value();
// relative rates and private parameters for mutations;
eoValueParam<double> pMutPerBitParam(0.01, "pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b');
parser.processParam( pMutPerBitParam, "Genetic Operators" );
double pMutPerBit = pMutPerBitParam.value();
eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B');
parser.processParam( bitFlipRateParam, "Genetic Operators" );
double bitFlipRate = bitFlipRateParam.value();
eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D');
parser.processParam( oneBitRateParam, "Genetic Operators" );
double oneBitRate = oneBitRateParam.value();
// the name of the "status" file where all actual parameter values will be saved
string str_status = parser.ProgramName() + ".status"; // default value
eoValueParam<string> statusParam(str_status.c_str(), "status","Status file",'S');
parser.processParam( statusParam, "Persistence" );
// do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
// i.e. in case you need parameters somewhere else, postpone these
if (parser.userNeedsHelp())
{
parser.printHelp(cout);
exit(1);
}
if (statusParam.value() != "")
{
ofstream os(statusParam.value().c_str());
os << parser; // and you can use that file as parameter file
}
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object ...
eoEvalFuncPtr<Indi, double, const vector<bool>& > plainEval( binary_value );
// ... to an object that counts the nb of actual evaluations
eoEvalFuncCounter<Indi> eval(plainEval);
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// Either load or initialize
// create an empty pop
eoPop<Indi> pop;
// create a state for reading
eoState inState; // a state for loading - WITHOUT the parser
// register the rng and the pop in the state, so they can be loaded,
// and the present run will be the exact conitnuation of the saved run
// eventually with different parameters
inState.registerObject(rng);
inState.registerObject(pop);
if (loadName != "")
{
inState.load(loadName); // load the pop and the rng
// the fitness is read in the file:
// do only evaluate the pop if the fitness has changed
}
else
{
rng.reseed(seed);
// a Indi random initializer
// based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(vecSize, uGen);
// Init pop from the randomizer: need to use the append function
pop.append(popSize, random);
// and evaluate pop (STL syntax)
apply<Indi>(eval, pop);
} // end of initializatio of the population
// OUTPUT
// sort pop for pretty printout
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl << pop << endl;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(tSize); // tSize in [2,POPSIZE]
// is now encapsulated in a eoSelectPerc (stands for Percentage)
eoSelectPerc<Indi> select(selectOne);
// REPLACE
// And we now have the full slection/replacement - though with
// the same generational replacement at the moment :-)
eoGenerationalReplacement<Indi> replace;
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// 1-point crossover for bitstring
eo1PtBitXover<Indi> xover1;
// uniform crossover for bitstring
eoUBitXover<Indi> xoverU;
// 2-pots xover
eoNPtsBitXover<Indi> xover2(2);
// Combine them with relative rates
eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
xover.add(xoverU, URate);
xover.add(xover2, twoPointsRate);
// MUTATION
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(pMutPerBit);
// mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, pCross, mutation, pMut);
// STOP
//////////////////////////////////////
// termination condition see FirstBitEA.cpp
/////////////////////////////////////
eoGenContinue<Indi> genCont(maxGen);
eoSteadyFitContinue<Indi> steadyCont(minGen, steadyGen);
eoFitContinue<Indi> fitCont(vecSize);
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// CHECKPOINT
// but now you want to make many different things every generation
// (e.g. statistics, plots, ...).
// the class eoCheckPoint is dedicated to just that:
// Declare a checkpoint (from a continuator: an eoCheckPoint
// IS AN eoContinue and will be called in the loop of all algorithms)
eoCheckPoint<Indi> checkpoint(continuator);
// Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference,
// so every time the incrementer is updated (every generation),
// the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value());
// Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation
checkpoint.add(increment);
// now some statistics on the population:
// Best fitness in population
eoBestFitnessStat<Indi> bestStat;
// Second moment stats: average and stdev
eoSecondMomentStats<Indi> SecondStat;
// Add them to the checkpoint to get them called at the appropriate time
checkpoint.add(bestStat);
checkpoint.add(SecondStat);
// The Stdout monitor will print parameters to the screen ...
eoStdoutMonitor monitor(false);
// when called by the checkpoint (i.e. at every generation)
checkpoint.add(monitor);
// the monitor will output a series of parameters: add them
monitor.add(generationCounter);
monitor.add(eval); // because now eval is an eoEvalFuncCounter!
monitor.add(bestStat);
monitor.add(SecondStat);
// A file monitor: will print parameters to ... a File, yes, you got it!
eoFileMonitor fileMonitor("stats.xg", " ");
// the checkpoint mechanism can handle multiple monitors
checkpoint.add(fileMonitor);
// the fileMonitor can monitor parameters, too, but you must tell it!
fileMonitor.add(generationCounter);
fileMonitor.add(bestStat);
fileMonitor.add(SecondStat);
// Last type of item the eoCheckpoint can handle: state savers:
eoState outState;
// Register the algorithm into the state (so it has something to save!!)
outState.registerObject(parser);
outState.registerObject(pop);
outState.registerObject(rng);
// and feed the state to state savers
// save state every 100th generation
eoCountedStateSaver stateSaver1(20, outState, "generation");
// save state every 1 seconds
eoTimedStateSaver stateSaver2(1, outState, "time");
// Don't forget to add the two savers to the checkpoint
checkpoint.add(stateSaver1);
checkpoint.add(stateSaver2);
// and that's it for the (control and) output
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// stopping criterion, eval, selection, transformation, replacement
eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,329 @@
//-----------------------------------------------------------------------------
// SecondRealEA.cpp
//-----------------------------------------------------------------------------
//*
// Same code than FirstBitEA as far as Evolutionary Computation is concerned
// but now you learn to enter the parameters in a more flexible way
// (also slightly different than in SecondBitEA.cpp)
// and to twidle the output to your preferences (as in SecondBitEA.cpp)
//
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <fstream>
#include <iostream> // cout
#include <stdexcept> // runtime_error
// the general include for eo
#include <paradiseo/eo.h>
#include <paradiseo/eo/es.h>
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your individuals
typedef eoReal<eoMinimizingFitness> Indi;
// Use functions from namespace std
using namespace std;
// EVALFUNC
//-----------------------------------------------------------------------------
// a simple fitness function that computes the euclidian norm of a real vector
// Now in a separate file, and declared as binary_value(const vector<bool> &)
#include "real_value.h"
// GENERAL
//-----------------------------------------------------------------------------
void main_function(int argc, char **argv)
{
// PARAMETRES
//-----------------------------------------------------------------------------
// instead of having all values of useful parameters as constants, read them:
// either on the command line (--option=value or -o=value)
// or in a parameter file (same syntax, order independent,
// # = usual comment character
// or in the environment (TODO)
// First define a parser from the command-line arguments
eoParser parser(argc, argv);
// For each parameter, you can in on single line
// define the parameter, read it through the parser, and assign it
unsigned seed = parser.createParam(unsigned(time(0)), "seed", "Random number seed", 'S').value(); // will be in default section General
// description of genotype
unsigned vecSize = parser.createParam(unsigned(8), "vecSize", "Genotype size",'V', "Representation" ).value();
// parameters for evolution engine
unsigned popSize = parser.createParam(unsigned(10), "popSize", "Population size",'P', "Evolution engine" ).value();
unsigned tSize = parser.createParam(unsigned(2), "tSize", "Tournament size",'T', "Evolution Engine" ).value();
// init and stop
string loadName = parser.createParam(string(""), "Load","A save file to restart from",'L', "Persistence" ).value();
unsigned maxGen = parser.createParam(unsigned(100), "maxGen", "Maximum number of generations",'G', "Stopping criterion" ).value();
unsigned minGen = parser.createParam(unsigned(100), "minGen", "Minimum number of generations",'g', "Stopping criterion" ).value();
unsigned steadyGen = parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion" ).value();
// operators probabilities at the algorithm level
double pCross = parser.createParam(double(0.6), "pCross", "Probability of Crossover", 'C', "Genetic Operators" ).value();
double pMut = parser.createParam(double(0.1), "pMut", "Probability of Mutation", 'M', "Genetic Operators" ).value();
// relative rates for crossovers
double hypercubeRate = parser.createParam(double(1), "hypercubeRate", "Relative rate for hypercube crossover", '\0', "Genetic Operators" ).value();
double segmentRate = parser.createParam(double(1), "segmentRate", "Relative rate for segment crossover", '\0', "Genetic Operators" ).value();
// internal parameters for the mutations
double EPSILON = parser.createParam(double(0.01), "EPSILON", "Width for uniform mutation", '\0', "Genetic Operators" ).value();
double SIGMA = parser.createParam(double(0.3), "SIGMA", "Sigma for normal mutation", '\0', "Genetic Operators" ).value();
// relative rates for mutations
double uniformMutRate = parser.createParam(double(1), "uniformMutRate", "Relative rate for uniform mutation", '\0', "Genetic Operators" ).value();
double detMutRate = parser.createParam(double(1), "detMutRate", "Relative rate for det-uniform mutation", '\0', "Genetic Operators" ).value();
double normalMutRate = parser.createParam(double(1), "normalMutRate", "Relative rate for normal mutation", '\0', "Genetic Operators" ).value();
// the name of the "status" file where all actual parameter values will be saved
string str_status = parser.ProgramName() + ".status"; // default value
string statusName = parser.createParam(str_status, "status","Status file",'S', "Persistence" ).value();
// do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
// i.e. in case you need parameters somewhere else, postpone these
if (parser.userNeedsHelp())
{
parser.printHelp(cout);
exit(1);
}
if (statusName != "")
{
ofstream os(statusName.c_str());
os << parser; // and you can use that file as parameter file
}
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object
// you need to give the full description of the function
eoEvalFuncPtr<Indi, double, const vector<double>& > plainEval( real_value );
// ... to an object that counts the nb of actual evaluations
eoEvalFuncCounter<Indi> eval(plainEval);
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// Either load or initialize
// create an empty pop
eoPop<Indi> pop;
// create a state for reading
eoState inState; // a state for loading - WITHOUT the parser
// register the rng and the pop in the state, so they can be loaded,
// and the present run will be the exact conitnuation of the saved run
// eventually with different parameters
inState.registerObject(rng);
inState.registerObject(pop);
if (loadName != "")
{
inState.load(loadName); // load the pop and the rng
// the fitness is read in the file:
// do only evaluate the pop if the fitness has changed
}
else
{
rng.reseed(seed);
// a Indi random initializer
// based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<double> uGen(-1.0, 1.0);
eoInitFixedLength<Indi> random(vecSize, uGen);
// Init pop from the randomizer: need to use the append function
pop.append(popSize, random);
// and evaluate pop (STL syntax)
apply<Indi>(eval, pop);
} // end of initializatio of the population
// OUTPUT
// sort pop before printing it!
pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl;
cout << pop;
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(tSize);
// is now encapsulated in a eoSelectPerc (entage)
eoSelectPerc<Indi> select(selectOne);// by default rate==1
// REPLACE
// And we now have the full slection/replacement - though with
// no replacement (== generational replacement) at the moment :-)
eoGenerationalReplacement<Indi> replace;
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// uniform chooce on segment made by the parents
eoSegmentCrossover<Indi> xoverS;
// uniform choice in hypercube built by the parents
eoHypercubeCrossover<Indi> xoverA;
// Combine them with relative weights
eoPropCombinedQuadOp<Indi> xover(xoverS, segmentRate);
xover.add(xoverA, hypercubeRate);
// MUTATION
// offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
eoUniformMutation<Indi> mutationU(EPSILON);
// k (=1) coordinates of parents are uniformly modified
eoDetUniformMutation<Indi> mutationD(EPSILON);
// all coordinates of parents are normally modified (stDev SIGMA)
eoNormalMutation<Indi> mutationN(SIGMA);
// Combine them with relative weights
eoPropCombinedMonOp<Indi> mutation(mutationU, uniformMutRate);
mutation.add(mutationD, detMutRate);
mutation.add(mutationN, normalMutRate, true);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, pCross, mutation, pMut);
// STOP
//////////////////////////////////////
// termination condition see FirstBitEA.cpp
/////////////////////////////////////
eoGenContinue<Indi> genCont(maxGen);
eoSteadyFitContinue<Indi> steadyCont(minGen, steadyGen);
eoFitContinue<Indi> fitCont(0);
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
continuator.add(fitCont);
// CHECKPOINT
// but now you want to make many different things every generation
// (e.g. statistics, plots, ...).
// the class eoCheckPoint is dedicated to just that:
// Declare a checkpoint (from a continuator: an eoCheckPoint
// IS AN eoContinue and will be called in the loop of all algorithms)
eoCheckPoint<Indi> checkpoint(continuator);
// Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference,
// so every time the incrementer is updated (every generation),
// the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value());
// Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation
checkpoint.add(increment);
// now some statistics on the population:
// Best fitness in population
eoBestFitnessStat<Indi> bestStat;
// Second moment stats: average and stdev
eoSecondMomentStats<Indi> SecondStat;
// Add them to the checkpoint to get them called at the appropriate time
checkpoint.add(bestStat);
checkpoint.add(SecondStat);
// The Stdout monitor will print parameters to the screen ...
eoStdoutMonitor monitor(false);
// when called by the checkpoint (i.e. at every generation)
checkpoint.add(monitor);
// the monitor will output a series of parameters: add them
monitor.add(generationCounter);
monitor.add(eval); // because now eval is an eoEvalFuncCounter!
monitor.add(bestStat);
monitor.add(SecondStat);
// A file monitor: will print parameters to ... a File, yes, you got it!
eoFileMonitor fileMonitor("stats.xg", " ");
// the checkpoint mechanism can handle multiple monitors
checkpoint.add(fileMonitor);
// the fileMonitor can monitor parameters, too, but you must tell it!
fileMonitor.add(generationCounter);
fileMonitor.add(bestStat);
fileMonitor.add(SecondStat);
// Last type of item the eoCheckpoint can handle: state savers:
eoState outState;
// Register the algorithm into the state (so it has something to save!!)
outState.registerObject(parser);
outState.registerObject(pop);
outState.registerObject(rng);
// and feed the state to state savers
// save state every 100th generation
eoCountedStateSaver stateSaver1(20, outState, "generation");
// save state every 1 seconds
eoTimedStateSaver stateSaver2(1, outState, "time");
// Don't forget to add the two savers to the checkpoint
checkpoint.add(stateSaver1);
checkpoint.add(stateSaver2);
// and that's it for the (control and) output
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// stopping criterion, eval, selection, transformation, replacement
eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,16 @@
#include <paradiseo/eo.h>
//-----------------------------------------------------------------------------
/** Just a simple function that takes binary value of a chromosome and sets
the fitnes.
@param _chrom A binary chromosome
*/
// INIT
double binary_value(const std::vector<bool>& _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum;
}

View file

@ -0,0 +1,404 @@
//-----------------------------------------------------------------------------
// SecondBitGA.cpp
//-----------------------------------------------------------------------------
//*
// Same code than FirstBitEA as far as Evolutionary Computation is concerned
// but now you learn to enter the parameters in a more flexible way
// and to twidle the output to your preferences!
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// standard includes
#include <fstream>
#include <iostream> // cout
#include <stdexcept> // runtime_error
// the general include for eo
#include <paradiseo/eo.h>
// EVAL
#include "binary_value.h"
// REPRESENTATION
//-----------------------------------------------------------------------------
// Include the corresponding file
#include <paradiseo/eo/ga.h> // bitstring representation & operators
// define your genotype and fitness types
typedef eoBit<eoMinimizingFitness> Indi;
using namespace std;
// the main_function: nothing changed(!), except variable initialization
void main_function(int argc, char **argv)
{
// PARAMETRES
//-----------------------------------------------------------------------------
// instead of having all values of useful parameters as constants, read them:
// either on the command line (--option=value or -o=value)
// or in a parameter file (same syntax, order independent,
// # = usual comment character
// or in the environment (TODO)
// First define a parser from the command-line arguments
eoParser parser(argc, argv);
// For each parameter, define Parameter, read it through the parser,
// and assign the value to the variable
eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam );
unsigned seed = seedParam.value();
// description of genotype
eoValueParam<unsigned int> vecSizeParam(100, "vecSize", "Genotype size",'V');
parser.processParam( vecSizeParam, "Representation" );
unsigned vecSize = vecSizeParam.value();
// parameters for evolution engine
eoValueParam<unsigned int> popSizeParam(100, "popSize", "Population size",'P');
parser.processParam( popSizeParam, "Evolution engine" );
unsigned popSize = popSizeParam.value();
eoValueParam<unsigned int> tSizeParam(10, "tSize", "Tournament size",'T');
parser.processParam( tSizeParam, "Evolution Engine" );
unsigned tSize = tSizeParam.value();
// init and stop
eoValueParam<string> loadNameParam("", "Load","A save file to restart from",'L');
parser.processParam( loadNameParam, "Persistence" );
string loadName = loadNameParam.value();
eoValueParam<unsigned int> maxGenParam(500, "maxGen", "Maximum number of generations",'G');
parser.processParam( maxGenParam, "Stopping criterion" );
unsigned maxGen = maxGenParam.value();
eoValueParam<unsigned int> minGenParam(500, "minGen", "Minimum number of generations",'g');
parser.processParam( minGenParam, "Stopping criterion" );
unsigned minGen = minGenParam.value();
eoValueParam<unsigned int> steadyGenParam(100, "steadyGen", "Number of generations with no improvement",'s');
parser.processParam( steadyGenParam, "Stopping criterion" );
unsigned steadyGen = steadyGenParam.value();
// operators probabilities at the algorithm level
eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C');
parser.processParam( pCrossParam, "Genetic Operators" );
double pCross = pCrossParam.value();
eoValueParam<double> pMutParam(0.1, "pMut", "Probability of Mutation", 'M');
parser.processParam( pMutParam, "Genetic Operators" );
double pMut = pMutParam.value();
// relative rates for crossovers
eoValueParam<double> onePointRateParam(1, "onePointRate", "Relative rate for one point crossover", '1');
parser.processParam( onePointRateParam, "Genetic Operators" );
double onePointRate = onePointRateParam.value();
eoValueParam<double> twoPointsRateParam(1, "twoPointRate", "Relative rate for two point crossover", '2');
parser.processParam( twoPointsRateParam, "Genetic Operators" );
double twoPointsRate = twoPointsRateParam.value();
eoValueParam<double> uRateParam(2, "uRate", "Relative rate for uniform crossover", 'U');
parser.processParam( uRateParam, "Genetic Operators" );
double URate = uRateParam.value();
// relative rates and private parameters for mutations;
eoValueParam<double> pMutPerBitParam(0.01, "pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b');
parser.processParam( pMutPerBitParam, "Genetic Operators" );
double pMutPerBit = pMutPerBitParam.value();
eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B');
parser.processParam( bitFlipRateParam, "Genetic Operators" );
double bitFlipRate = bitFlipRateParam.value();
eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D');
parser.processParam( oneBitRateParam, "Genetic Operators" );
double oneBitRate = oneBitRateParam.value();
// the name of the "status" file where all actual parameter values will be saved
string str_status = parser.ProgramName() + ".status"; // default value
eoValueParam<string> statusParam(str_status.c_str(), "status","Status file",'S');
parser.processParam( statusParam, "Persistence" );
// do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
// i.e. in case you need parameters somewhere else, postpone these
if (parser.userNeedsHelp())
{
parser.printHelp(cout);
exit(1);
}
if (statusParam.value() != "")
{
ofstream os(statusParam.value().c_str());
os << parser; // and you can use that file as parameter file
}
// EVAL
/////////////////////////////
// Fitness function
////////////////////////////
// Evaluation: from a plain C++ fn to an EvalFunc Object ...
eoEvalFuncPtr<Indi, double, const vector<bool>& > plainEval( binary_value );
// ... to an object that counts the nb of actual evaluations
eoEvalFuncCounter<Indi> eval(plainEval);
// INIT
////////////////////////////////
// Initilisation of population
////////////////////////////////
// Either load or initialize
// create an empty pop
eoPop<Indi> pop;
// create a state for reading
eoState inState; // a state for loading - WITHOUT the parser
// register the rng and the pop in the state, so they can be loaded,
// and the present run will be the exact conitnuation of the saved run
// eventually with different parameters
inState.registerObject(rng);
inState.registerObject(pop);
if (loadName != "")
{
inState.load(loadName); // load the pop and the rng
// the fitness is read in the file:
// do only evaluate the pop if the fitness has changed
}
else
{
rng.reseed(seed);
// a Indi random initializer
// based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(vecSize, uGen);
// Init pop from the randomizer: need to use the append function
pop.append(popSize, random);
// and evaluate pop (STL syntax)
apply<Indi>(eval, pop);
} // end of initializatio of the population
// OUTPUT
// sort pop for pretty printout
// pop.sort();
// Print (sorted) intial population (raw printout)
cout << "Initial Population" << endl << pop ;
cout << "and best is " << pop.best_element() << "\n\n";
cout << "and worse is " << pop.worse_element() << "\n\n";
// ENGINE
/////////////////////////////////////
// selection and replacement
////////////////////////////////////
// SELECT
// The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(tSize); // tSize in [2,POPSIZE]
// is now encapsulated in a eoSelectPerc (entage)
eoSelectPerc<Indi> select(selectOne);// by default rate==1
// REPLACE
// And we now have the full slection/replacement - though with
// generational replacement at the moment :-)
eoGenerationalReplacement<Indi> replace;
// want to add (weak) elitism? easy!
// rename the eoGenerationalReplacement replace_main,
// then encapsulate it in the elitist replacement
// eoWeakElitistReplacement<Indi> replace(replace_main);
// OPERATORS
//////////////////////////////////////
// The variation operators
//////////////////////////////////////
// CROSSOVER
// 1-point crossover for bitstring
eo1PtBitXover<Indi> xover1;
// uniform crossover for bitstring
eoUBitXover<Indi> xoverU;
// 2-pots xover
eoNPtsBitXover<Indi> xover2(2);
// Combine them with relative rates
eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
xover.add(xoverU, URate);
xover.add(xover2, twoPointsRate);
// MUTATION
// standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(pMutPerBit);
// mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true);
// The operators are encapsulated into an eoTRansform object
eoSGATransform<Indi> transform(xover, pCross, mutation, pMut);
// STOP
//////////////////////////////////////
// termination condition see FirstBitEA.cpp
/////////////////////////////////////
eoGenContinue<Indi> genCont(maxGen);
eoSteadyFitContinue<Indi> steadyCont(minGen, steadyGen);
// eoFitContinue<Indi> fitCont(vecSize); // remove if minimizing :-)
eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont);
// continuator.add(fitCont);
// Ctrl C signal handling: don't know if that works in MSC ...
#ifndef _MSC_VER
eoCtrlCContinue<Indi> ctrlC;
continuator.add(ctrlC);
#endif
// CHECKPOINT
// but now you want to make many different things every generation
// (e.g. statistics, plots, ...).
// the class eoCheckPoint is dedicated to just that:
// Declare a checkpoint (from a continuator: an eoCheckPoint
// IS AN eoContinue and will be called in the loop of all algorithms)
eoCheckPoint<Indi> checkpoint(continuator);
// Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference,
// so every time the incrementer is updated (every generation),
// the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value());
// Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation
checkpoint.add(increment);
// now some statistics on the population:
// Best fitness in population
eoBestFitnessStat<Indi> bestStat;
eoAverageStat<Indi> averageStat;
// Second moment stats: average and stdev
eoSecondMomentStats<Indi> SecondStat;
// the Fitness Distance Correlation
// need first an object to compute the distances
eoQuadDistance<Indi> dist; // Hamming distance
eoFDCStat<Indi> fdcStat(dist);
// Add them to the checkpoint to get them called at the appropriate time
checkpoint.add(bestStat);
checkpoint.add(averageStat);
checkpoint.add(SecondStat);
checkpoint.add(fdcStat);
// The Stdout monitor will print parameters to the screen ...
eoStdoutMonitor monitor(false);
// when called by the checkpoint (i.e. at every generation)
checkpoint.add(monitor);
// the monitor will output a series of parameters: add them
monitor.add(generationCounter);
monitor.add(eval); // because now eval is an eoEvalFuncCounter!
monitor.add(bestStat);
monitor.add(SecondStat);
monitor.add(fdcStat);
// test de eoPopStat and/or eoSortedPopStat.
// Dumps the whole pop every 10 gen.
// eoSortedPopStat<Indi> popStat(10, "Dump of whole population");
// eoPopStat<Indi> popStat(10, "Dump of whole population");
// checkpoint.add(popStat);
// monitor.add(popStat);
// A file monitor: will print parameters to ... a File, yes, you got it!
eoFileMonitor fileMonitor("stats.xg", " ");
// the checkpoint mechanism can handle monitors
checkpoint.add(fileMonitor);
// the fileMonitor can monitor parameters, too, but you must tell it!
fileMonitor.add(generationCounter);
fileMonitor.add(bestStat);
fileMonitor.add(SecondStat);
#ifndef _MSC_VER
// and an eoGnuplot1DMonitor will 1-print to a file, and 2- plot on screen
eoGnuplot1DMonitor gnuMonitor("best_average.xg",minimizing_fitness<Indi>());
// the checkpoint mechanism can handle multiple monitors
checkpoint.add(gnuMonitor);
// the gnuMonitor can monitor parameters, too, but you must tell it!
gnuMonitor.add(eval);
gnuMonitor.add(bestStat);
gnuMonitor.add(averageStat);
// send a scaling command to gnuplot
gnuMonitor.gnuplotCommand("set yrange [0:500]");
// a specific plot monitor for FDC
// first into a file (it adds everything ti itself
eoFDCFileSnapshot<Indi> fdcFileSnapshot(fdcStat);
// then to a Gnuplot monitor
eoGnuplot1DSnapshot fdcGnuplot(fdcFileSnapshot);
// and of coruse add them to the checkPoint
checkpoint.add(fdcFileSnapshot);
checkpoint.add(fdcGnuplot);
// want to see how the fitness is spread?
eoScalarFitnessStat<Indi> fitStat;
checkpoint.add(fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name
// where to store the files
eoGnuplot1DSnapshot fitSnapshot("Fitnesses");
// add any stat that is a vector<double> to it
fitSnapshot.add(fitStat);
// and of course add it to the checkpoint
checkpoint.add(fitSnapshot);
#endif
// Last type of item the eoCheckpoint can handle: state savers:
eoState outState;
// Register the algorithm into the state (so it has something to save!!)
outState.registerObject(rng);
outState.registerObject(pop);
// and feed the state to state savers
// save state every 100th generation
eoCountedStateSaver stateSaver1(100, outState, "generation");
// save state every 1 seconds
eoTimedStateSaver stateSaver2(1, outState, "time");
// Don't forget to add the two savers to the checkpoint
checkpoint.add(stateSaver1);
checkpoint.add(stateSaver2);
// and that's it for the (control and) output
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// Easy EA requires
// selection, transformation, eval, replacement, and stopping criterion
eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
// Apply algo to pop - that's it!
gga(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL Population\n" << pop << endl;
// GENERAL
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}

View file

@ -0,0 +1,17 @@
#include <vector>
//-----------------------------------------------------------------------------
/** Just a simple function that takes an vector<double> and sets the fitnes
to the sphere function. Please use doubles not float!!!
@param _ind A floatingpoint vector
*/
// INIT
double real_value(const std::vector<double>& _ind)
{
double sum = 0;
for (unsigned i = 0; i < _ind.size(); i++)
{
sum += _ind[i] * _ind[i];
}
return sum;
}

95
tutorial/eo/Lesson4/BitEA.cpp Executable file
View file

@ -0,0 +1,95 @@
#include <iostream>
#include <paradiseo/eo/ga/make_ga.h>
#include <paradiseo/eo/apply.h>
// EVAL
#include "binary_value.h"
// GENERAL
using namespace std;
int main(int argc, char* argv[])
{
try
{
// REPRESENTATION
//-----------------------------------------------------------------------------
// define your genotype and fitness types
typedef eoBit<double> EOT;
// PARAMETRES
eoParser parser(argc, argv); // for user-parameter reading
// GENERAL
eoState state; // keeps all things allocated
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// EVAL
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double> mainEval( binary_value<EOT> );
eoEvalFuncCounter<EOT> eval(mainEval);
// REPRESENTATION
// the genotype - through a genotype initializer
eoInit<EOT>& init = make_genotype(parser, state, EOT());
// if you want to do sharing, you'll need a distance.
// here Hamming distance
eoHammingDistance<EOT> dist;
// OPERATORS
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(parser, state, init);
// GENERAL
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(parser, state, init);
// STOP
// stopping criteria
eoContinue<EOT> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval, term);
// GENERATION
// algorithm (need the operator!)
eoAlgo<EOT>& ga = make_algo_scalar(parser, state, eval, checkpoint, op, &dist);
///// End of construction of the algorith
/////////////////////////////////////////
// PARAMETRES
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// EVAL
// evaluate intial population AFTER help and status in case it takes time
apply<EOT>(eval, pop);
// STOP
// print it out (sort witout modifying)
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
// GENERATION
run_ea(ga, pop); // run the ga
// STOP
// print it out (sort witout modifying)
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
// GENERAL
}
catch(exception& e)
{
cout << e.what() << endl;
}
}

View file

@ -0,0 +1,98 @@
######################################################################################
### 0) Copy the ESEA.param and RealEA.param files in the build directory for an easy use.
######################################################################################
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${EO_TUTORIAL_DIR}/Lesson4/ESEA.param
${EO_BIN_DIR}/tutorial/Lesson4/ESEA.param
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${EO_TUTORIAL_DIR}/Lesson4/RealEA.param
${EO_BIN_DIR}/tutorial/Lesson4/RealEA.param
)
##############
# OLD_TARGETS
##############
#add_custom_target(param DEPENDS ${EO_SRC_DIR}/tutorial/Lesson4/ESEA.param)
#add_custom_command(
# TARGET param
# POST_BUILD
# COMMAND ${CMAKE_COMMAND}
# ARGS -E copy_if_different
# ${EO_SRC_DIR}/tutorial/Lesson4/ESEA.param
# ${EO_BIN_DIR}/tutorial/Lesson4)
#add_custom_target(param DEPENDS ${EO_SRC_DIR}/tutorial/Lesson4/RealEA.param)
#add_custom_command(
# TARGET param
# POST_BUILD
# COMMAND ${CMAKE_COMMAND}
# ARGS -E copy_if_different
# ${EO_SRC_DIR}/tutorial/Lesson4/RealEA.param
# ${EO_BIN_DIR}/tutorial/Lesson4)
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${EO_SRC_DIR}/src/es)
#include_directories(${EO_SRC_DIR}/src/utils)
#include_directories(${EO_SRC_DIR}/src/ga)
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
# no matter what is the OS, hopefully
add_executable(BitEA BitEA.cpp)
add_executable(RealEA RealEA.cpp)
add_executable(ESEA ESEA.cpp)
#add_dependencies(BitEA es ga eo eoutils)
#add_dependencies(RealEA es ga eo eoutils)
#add_dependencies(ESEA es ga eo eoutils)
######################################################################################
### 4) Optionnal
######################################################################################
set(BITEA_VERSION ${GLOBAL_VERSION})
set_target_properties(BitEA PROPERTIES VERSION "${BITEA_VERSION}")
set(REALEA_VERSION ${GLOBAL_VERSION})
set_target_properties(RealEA PROPERTIES VERSION "${REALEA_VERSION}")
set(ESEA_VERSION ${GLOBAL_VERSION})
set_target_properties(ESEA PROPERTIES VERSION "${ESEA_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(BitEA es ga eo eoutils)
target_link_libraries(RealEA es ga eo eoutils)
target_link_libraries(ESEA es ga eo eoutils)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS BitEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson4 COMPONENT examples)
install(TARGETS RealEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson4 COMPONENT examples)
install(TARGETS ESEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson4 COMPONENT examples)
######################################################################################

137
tutorial/eo/Lesson4/ESEA.cpp Executable file
View file

@ -0,0 +1,137 @@
// Program to test several EO-ES features
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <time.h>
using namespace std;
#include <paradiseo/eo.h>
// representation specific
#include <paradiseo/eo/es/make_es.h>
#include "real_value.h" // the sphere fitness
// Now the main
///////////////
typedef eoMinimizingFitness FitT;
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state);
int main_function(int argc, char *argv[])
{
// Create the command-line parser
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
eoValueParam<bool>& simpleParam = parser.createParam(true, "Isotropic", "Isotropic self-adaptive mutation", 'i', "ES mutation");
eoValueParam<bool>& stdevsParam = parser.createParam(false, "Stdev", "One self-adaptive stDev per variable", 's', "ES mutation");
eoValueParam<bool>& corrParam = parser.createParam(false, "Correl", "Use correlated mutations", 'c', "ES mutation");
// Run the appropriate algorithm
if (simpleParam.value() == false)
{
cout << "Using eoReal" << endl;
runAlgorithm(eoReal<FitT>(), parser, state);
}
else if (stdevsParam.value() == false)
{
cout << "Using eoEsSimple" << endl;
runAlgorithm(eoEsSimple<FitT>(), parser, state);
}
else if (corrParam.value() == false)
{
cout << "Using eoEsStdev" << endl;
runAlgorithm(eoEsStdev<FitT>(), parser, state);
}
else
{
cout << "Using eoEsFull" << endl;
runAlgorithm(eoEsFull<FitT>(), parser, state);
}
return 0;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}
/** The templatized main (sort of)
* quite similar to the main of other genotypes
* (e.g. t-eoReal and t-eoGA in test dir)
*/
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state)
{
typedef typename EOT::Fitness FitT;
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double, const std::vector<double>&>
mainEval( real_value );
eoEvalFuncCounter<EOT> eval(mainEval);
// the genotype - through a genotype initializer
eoRealInitBounded<EOT>& init = make_genotype(_parser, _state, EOT());
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(_parser, _state, init);
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(_parser, _state, init);
apply<EOT>(eval, pop);
// stopping criteria
eoContinue<EOT> & term = make_continue(_parser, _state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(_parser, _state, eval, term);
// algorithm (need the operator!)
eoAlgo<EOT>& ga = make_algo_scalar(_parser, _state, eval, checkpoint, op);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(_parser);
//// GO
///////
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
run_ea(ga, pop); // run the ga
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
}

61
tutorial/eo/Lesson4/ESEA.param Executable file
View file

@ -0,0 +1,61 @@
###### General ######
# --help=0 # -h : Prints this message
# --stopOnUnknownParam=1 # Stop if unkown param entered
# --seed=1104133126 # -S : Random number seed
###### ES mutation ######
# --Isotropic=1 # -i : Isotropic self-adaptive mutation
# --Stdev=0 # -s : One self-adaptive stDev per variable
# --Correl=0 # -c : Use correlated mutations
###### Evolution Engine ######
--popSize=1 # -P : Population Size
--selection=Sequential # -S : Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)
--nbOffspring=700% # -O : Nb of offspring (percentage or absolute)
--replacement=Comma # -R : Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t)
--weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary*
###### Genotype Initialization ######
# --vecSize=10 # -n : The number of variables
# --initBounds=10[-1,1] # -B : Bounds for initialization (MUST be bounded)
--sigmaInit=0.3% # -s : Initial value for Sigmas (with a '%' -> scaled by the range of each variable)
###### Output ######
# --useEval=1 # Use nb of eval. as counter (vs nb of gen.)
# --useTime=1 # Display time (s) every generation
# --printBestStat=1 # Print Best/avg/stdev every gen.
# --printPop=0 # Print sorted pop. every gen.
###### Output - Disk ######
# --resDir=Res # Directory to store DISK outputs
# --eraseDir=1 # erase files in dirName if any
# --fileBestStat=0 # Output bes/avg/std to file
###### Output - Graphical ######
# --plotBestStat=0 # Plot Best/avg Stat
# --plotHisto=0 # Plot histogram of fitnesses
###### Persistence ######
# --Load= # -L : A save file to restart from
# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.?
# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never)
# --saveTimeInterval=0 # Save every T seconds (0 or absent = never)
# --status=t-eoESAll.status # Status file
###### Stopping criterion ######
# --maxGen=100 # -G : Maximum number of generations () = none)
# --steadyGen=100 # -s : Number of generations with no improvement
# --minGen=0 # -g : Minimum number of generations
# --maxEval=0 # -E : Maximum number of evaluations (0 = none)
# --targetFitness=0 # -T : Stop when fitness reaches
# --CtrlC=0 # -C : Terminate current generation upon Ctrl C
###### Variation Operators ######
# --objectBounds=10[-inf,+inf] # -B : Bounds for variables
# --operator=SGA # -o : Description of the operator (SGA only now)
# --pCross=1 # -C : Probability of Crossover
# --pMut=1 # -M : Probability of Mutation
# --crossType=global # -C : Type of ES recombination (global or standard)
# --crossObj=discrete # -O : Recombination of object variables (discrete, intermediate or none)
# --crossStdev=intermediate # -S : Recombination of mutation strategy parameters (intermediate, discrete or none)
# --TauLoc=1 # -l : Local Tau (before normalization)

View file

@ -0,0 +1,33 @@
### This Makefile is part of the tutorial of the EO library
# Unlike other Makefiles in EO, it is not using the automake/autoconf
# so that it stays easy to understant (you are in the tutorial, remember!)
# MS, Oct. 2002
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp
ALL = BitEA RealEA ESEA
all : $(ALL)
BitEA : BitEA.o ;
$(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/ga/libga.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
RealEA : RealEA.o ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/es/libes.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
ESEA : ESEA.o ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/es/libes.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
clean :
@/bin/rm $(ALL) *.o *.sav *.xg *.status *~

72
tutorial/eo/Lesson4/RealEA.cpp Executable file
View file

@ -0,0 +1,72 @@
#include <iostream>
#include <paradiseo/eo/es/make_real.h>
#include "real_value.h"
#include <paradiseo/eo/apply.h>
using namespace std;
int main(int argc, char* argv[])
{
try
{
typedef eoReal<eoMinimizingFitness> EOT;
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double, const std::vector<double>&>
mainEval( real_value );
eoEvalFuncCounter<EOT> eval(mainEval);
// the genotype - through a genotype initializer
eoRealInitBounded<EOT>& init = make_genotype(parser, state, EOT());
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(parser, state, init);
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(parser, state, init);
// stopping criteria
eoContinue<EOT> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<EOT>& ea = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<EOT>(eval, pop);
// print it out
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
run_ea(ea, pop); // run the ea
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
}
catch(exception& e)
{
cout << e.what() << endl;
}
}

View file

@ -0,0 +1,56 @@
###### General ######
# --help=0 # -h : Prints this message
# --stopOnUnknownParam=1 # Stop if unkown param entered
# --seed=1104133126 # -S : Random number seed
###### Evolution Engine ######
--popSize=10 # -P : Population Size
--selection=Sequential # -S : Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)
--nbOffspring=700% # -O : Nb of offspring (percentage or absolute)
--replacement=Plus # -R : Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t)
--weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary*
###### Genotype Initialization ######
# --vecSize=10 # -n : The number of variables
# --initBounds=10[-1,1] # -B : Bounds for initialization (MUST be bounded)
--sigmaInit=0.3% # -s : Initial value for Sigmas (with a '%' -> scaled by the range of each variable)
###### Output ######
# --useEval=1 # Use nb of eval. as counter (vs nb of gen.)
# --useTime=1 # Display time (s) every generation
# --printBestStat=1 # Print Best/avg/stdev every gen.
# --printPop=0 # Print sorted pop. every gen.
###### Output - Disk ######
# --resDir=Res # Directory to store DISK outputs
# --eraseDir=1 # erase files in dirName if any
# --fileBestStat=0 # Output bes/avg/std to file
###### Output - Graphical ######
# --plotBestStat=0 # Plot Best/avg Stat
# --plotHisto=0 # Plot histogram of fitnesses
###### Persistence ######
# --Load= # -L : A save file to restart from
# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.?
# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never)
# --saveTimeInterval=0 # Save every T seconds (0 or absent = never)
# --status=t-eoESAll.status # Status file
###### Stopping criterion ######
# --maxGen=100 # -G : Maximum number of generations () = none)
# --steadyGen=100 # -s : Number of generations with no improvement
# --minGen=0 # -g : Minimum number of generations
# --maxEval=0 # -E : Maximum number of evaluations (0 = none)
# --targetFitness=0 # -T : Stop when fitness reaches
# --CtrlC=0 # -C : Terminate current generation upon Ctrl C
###### Variation Operators ######
# --objectBounds=10[-inf,+inf] # -B : Bounds for variables
# --operator=SGA # -o : Description of the operator (SGA only now)
# --pCross=1 # -C : Probability of Crossover
# --pMut=1 # -M : Probability of Mutation
# --crossType=global # -C : Type of ES recombination (global or standard)
# --crossObj=discrete # -O : Recombination of object variables (discrete, intermediate or none)
# --crossStdev=intermediate # -S : Recombination of mutation strategy parameters (intermediate, discrete or none)
# --TauLoc=1 # -l : Local Tau (before normalization)

View file

@ -0,0 +1,25 @@
#include <paradiseo/eo.h>
//-----------------------------------------------------------------------------
/** Just a simple function that takes binary value of a chromosome and sets
the fitnes.
@param _chrom A binary chromosome
*/
template <class Chrom> double binary_value(const Chrom& _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
if (_chrom[i])
sum += _chrom[i];
return sum;
}
struct BinaryValue
{
template <class Chrom> void operator()(Chrom& _chrom)
{
_chrom.fitness(binary_value(_chrom));
}
};

View file

@ -0,0 +1,16 @@
#include <vector>
//-----------------------------------------------------------------------------
/** Just a simple function that takes an eoEsBase<double> and sets the fitnes
to sphere
@param _ind vector<double>
*/
double real_value(const std::vector<double>& _ind)
{
double sum = 0;
for (unsigned i = 0; i < _ind.size(); i++)
sum += _ind[i] * _ind[i];
return sqrt(sum);
}

View file

@ -0,0 +1,56 @@
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
#include_directories(${CMAKE_CURRENT_SOURCE_DIR})
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
# no matter what is the OS, hopefully
add_executable(OneMaxEA OneMaxEA.cpp)
add_executable(OneMaxLibEA OneMaxLibEA.cpp make_OneMax.cpp)
add_dependencies(OneMaxEA es ga eo eoutils)
add_dependencies(OneMaxLibEA es ga eo eoutils)
######################################################################################
### 4) Optionnal
######################################################################################
set(ONEMAXEA_VERSION ${GLOBAL_VERSION})
set_target_properties(OneMaxEA PROPERTIES VERSION "${ONEMAXEA_VERSION}")
set(ONEMAXLIBEA_VERSION ${GLOBAL_VERSION})
set_target_properties(OneMaxLibEA PROPERTIES VERSION "${ONEMAXLIBEA_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(OneMaxEA es ga eo eoutils)
target_link_libraries(OneMaxLibEA es ga eo eoutils)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS OneMaxEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson5 COMPONENT examples)
install(TARGETS OneMaxLibEA RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson5 COMPONENT examples)
######################################################################################

View file

@ -0,0 +1,56 @@
### This Makefile is part of the tutorial of the EO library
# Unlike other Makefiles in EO, it is not using the automake/autoconf
# so that it stays easy to understant (you are in the tutorial, remember!)
# MS, Oct. 2002
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp
# local sources
COMMON_SOURCES = eoOneMax.h \
eoOneMaxEvalFunc.h \
eoOneMaxInit.h \
eoOneMaxMutation.h \
eoOneMaxQuadCrossover.h \
make_genotype_OneMax.h \
make_op_OneMax.h
NO_LIB_SOURCES = OneMaxEA.cpp
LIB_SOURCES = OneMaxLibEA.cpp make_OneMax.cpp
SOURCES = $(COMMON_SOURCES) OneMaxEA.cpp OneMaxLibEA.cpp make_OneMax.cpp
LIB_EO = $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
ALL = OneMaxEA OneMaxLibEA
OneMaxEA : OneMaxEA.o
$(CXX) -g -o $@ OneMaxEA.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm
OneMaxLibEA : OneMaxLibEA.o make_OneMax.o
$(CXX) -g -o $@ OneMaxLibEA.o make_OneMax.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm
tar : ; tar czvf OneMax.tgz *.h *.cpp Makefile
all : $(ALL)
clean : ; /bin/rm *.o $(ALL)
########## local dependencies
OneMaxEA.o : $(COMMON_SOURCES) OneMaxEA.cpp
OneMaxLibEA.o : $(COMMON_SOURCES) OneMaxLibEA.cpp
make_OneMax.o : make_OneMax.cpp eoOneMax.h

188
tutorial/eo/Lesson5/OneMaxEA.cpp Executable file
View file

@ -0,0 +1,188 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for creating a new representation in EO
================================================
This is the template main file.
It includes all other files that have been generated by the script create.sh
so it is the only file to compile.
In case you want to build up a separate library for your new Evolving Object,
you'll need some work - follow what's done in the src/ga dir, used in the
main file BitEA in tutorial/Lesson4 dir.
Or you can wait until we do it :-)
*/
// Miscilaneous include and declaration
#include <iostream>
using namespace std;
// eo general include
#include <paradiseo/eo.h>
// the real bounds (not yet in general eo include)
#include <paradiseo/eo/utils/eoRealVectorBounds.h>
// include here whatever specific files for your representation
// Basically, this should include at least the following
/** definition of representation:
* class eoOneMax MUST derive from EO<FitT> for some fitness
*/
#include "eoOneMax.h"
/** definition of initilizqtion:
* class eoOneMaxInit MUST derive from eoInit<eoOneMax>
*/
#include "eoOneMaxInit.h"
/** definition of evaluation:
* class eoOneMaxEvalFunc MUST derive from eoEvalFunc<eoOneMax>
* and should test for validity before doing any computation
* see tutorial/Templates/evalFunc.tmpl
*/
#include "eoOneMaxEvalFunc.h"
// GENOTYPE eoOneMax ***MUST*** be templatized over the fitness
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// START fitness type: double or eoMaximizingFitness if you are maximizing
// eoMinimizingFitness if you are minimizing
typedef eoMaximizingFitness MyFitT ; // type of fitness
// END fitness type
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Then define your EO objects using that fitness type
typedef eoOneMax<MyFitT> Indi; // ***MUST*** derive from EO
// create an initializer
#include "make_genotype_OneMax.h"
eoInit<Indi> & make_genotype(eoParser& _parser, eoState&_state, Indi _eo)
{
return do_make_genotype(_parser, _state, _eo);
}
// and the variation operaotrs
#include "make_op_OneMax.h"
eoGenOp<Indi>& make_op(eoParser& _parser, eoState& _state, eoInit<Indi>& _init)
{
return do_make_op(_parser, _state, _init);
}
// Use existing modules to define representation independent routines
// These are parser-based definitions of objects
// how to initialize the population
// it IS representation independent if an eoInit is given
#include <paradiseo/eo/do/make_pop.h>
eoPop<Indi >& make_pop(eoParser& _parser, eoState& _state, eoInit<Indi> & _init)
{
return do_make_pop(_parser, _state, _init);
}
// the stopping criterion
#include <paradiseo/eo/do/make_continue.h>
eoContinue<Indi>& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval)
{
return do_make_continue(_parser, _state, _eval);
}
// outputs (stats, population dumps, ...)
#include <paradiseo/eo/do/make_checkpoint.h>
eoCheckPoint<Indi>& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi>& _eval, eoContinue<Indi>& _continue)
{
return do_make_checkpoint(_parser, _state, _eval, _continue);
}
// evolution engine (selection and replacement)
#include <paradiseo/eo/do/make_algo_scalar.h>
eoAlgo<Indi>& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<Indi>& _eval, eoContinue<Indi>& _continue, eoGenOp<Indi>& _op)
{
return do_make_algo_scalar(_parser, _state, _eval, _continue, _op);
}
// simple call to the algo. stays there for consistency reasons
// no template for that one
#include <paradiseo/eo/do/make_run.h>
// the instanciating fitnesses
#include <paradiseo/eo/eoScalarFitness.h>
void run_ea(eoAlgo<Indi>& _ga, eoPop<Indi>& _pop)
{
do_run(_ga, _pop);
}
// checks for help demand, and writes the status file
// and make_help; in libutils
void make_help(eoParser & _parser);
// now use all of the above, + representation dependent things
int main(int argc, char* argv[])
{
try
{
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
// The fitness
//////////////
eoOneMaxEvalFunc<Indi> plainEval/* (varType _anyVariable) */;
// turn that object into an evaluation counter
eoEvalFuncCounter<Indi> eval(plainEval);
// the genotype - through a genotype initializer
eoInit<Indi>& init = make_genotype(parser, state, Indi());
// Build the variation operator (any seq/prop construct)
eoGenOp<Indi>& op = make_op(parser, state, init);
//// Now the representation-independent things
//
// YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT
// unless you want to add specific statistics to the checkpoint
//////////////////////////////////////////////
// initialize the population
// yes, this is representation indepedent once you have an eoInit
eoPop<Indi>& pop = make_pop(parser, state, init);
// stopping criteria
eoContinue<Indi> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<Indi> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<Indi>& ga = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorithm
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<Indi>(eval, pop);
// if you want to print it out
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
run_ea(ga, pop); // run the ga
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
}
catch(exception& e)
{
cout << e.what() << endl;
}
return 0;
}

View file

@ -0,0 +1,162 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for creating a new representation in EO
================================================
This is the template main file for compiling after creating a
library.
See make_OneMax.cpp file.
*/
// Miscilaneous include and declaration
#include <iostream>
using namespace std;
// eo general include
#include <paradiseo/eo.h>
// the real bounds (not yet in general eo include)
#include <paradiseo/eo/utils/eoRealVectorBounds.h>
// include here whatever specific files for your representation
// Basically, this should include at least the following
/** definition of representation:
* class eoOneMax MUST derive from EO<FitT> for some fitness
*/
#include "eoOneMax.h"
/** definition of initilizqtion:
* class eoOneMaxInit MUST derive from eoInit<eoOneMax>
*/
#include "eoOneMaxInit.h"
/** definition of evaluation:
* class eoOneMaxEvalFunc MUST derive from eoEvalFunc<eoOneMax>
* and should test for validity before doing any computation
* see tutorial/Templates/evalFunc.tmpl
*/
#include "eoOneMaxEvalFunc.h"
// GENOTYPE eoOneMax ***MUST*** be templatized over the fitness
//
// START fitness type: double or eoMaximizingFitness if you are maximizing
// eoMinimizingFitness if you are minimizing
typedef eoMinimizingFitness MyFitT ; // type of fitness
// END fitness type
//
// Then define your EO objects using that fitness type
typedef eoOneMax<MyFitT> Indi; // ***MUST*** derive from EO
// create an initializer - done here and NOT in make_OneMax.cpp
// because it is NOT representation independent
#include "make_genotype_OneMax.h"
eoInit<Indi> & make_genotype(eoParser& _parser, eoState&_state, Indi _eo)
{
return do_make_genotype(_parser, _state, _eo);
}
// same thing for the variation operaotrs
#include "make_op_OneMax.h"
eoGenOp<Indi>& make_op(eoParser& _parser, eoState& _state, eoInit<Indi>& _init)
{
return do_make_op(_parser, _state, _init);
}
// The representation independent routines are simply declared here
// how to initialize the population
// it IS representation independent if an eoInit is given
eoPop<Indi >& make_pop(eoParser& _parser, eoState& _state, eoInit<Indi> & _init);
// the stopping criterion
eoContinue<Indi>& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval);
// outputs (stats, population dumps, ...)
eoCheckPoint<Indi>& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi>& _eval, eoContinue<Indi>& _continue);
// evolution engine (selection and replacement)
eoAlgo<Indi>& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<Indi>& _eval, eoContinue<Indi>& _continue, eoGenOp<Indi>& _op);
// simple call to the algo. stays there for consistency reasons
// no template for that one
void run_ea(eoAlgo<Indi>& _ga, eoPop<Indi>& _pop);
// checks for help demand, and writes the status file
// and make_help; in libutils - just a declaration, code in libeoutils.a
void make_help(eoParser & _parser);
// now use all of the above, + representation dependent things
// from here on, no difference with eoOneMax.cpp
int main(int argc, char* argv[])
{
try
{
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
// The fitness
//////////////
eoOneMaxEvalFunc<Indi> plainEval/* (varType _anyVariable) */;
// turn that object into an evaluation counter
eoEvalFuncCounter<Indi> eval(plainEval);
// the genotype - through a genotype initializer
eoInit<Indi>& init = make_genotype(parser, state, Indi());
// Build the variation operator (any seq/prop construct)
eoGenOp<Indi>& op = make_op(parser, state, init);
//// Now the representation-independent things
//
// YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT
// unless you want to add specific statistics to the checkpoint
//////////////////////////////////////////////
// initialize the population
// yes, this is representation indepedent once you have an eoInit
eoPop<Indi>& pop = make_pop(parser, state, init);
// stopping criteria
eoContinue<Indi> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<Indi> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<Indi>& ga = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorithm
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<Indi>(eval, pop);
// if you want to print it out
cout << "Initial Population\n";
pop.sortedPrintOn(cout);
cout << endl;
run_ea(ga, pop); // run the ga
cout << "Final Population\n";
pop.sortedPrintOn(cout);
cout << endl;
}
catch(exception& e)
{
cout << e.what() << endl;
}
return 0;
}

110
tutorial/eo/Lesson5/eoOneMax.h Executable file
View file

@ -0,0 +1,110 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for creating a new representation in EO
================================================
*/
#ifndef _eoOneMax_h
#define _eoOneMax_h
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
* Note that you MUST derive your structure from EO<fitT>
* but you MAY use some other already prepared class in the hierarchy
* like eoVector for instance, if you handle a vector of something....
* If you create a structure from scratch,
* the only thing you need to provide are
* a default constructor
* IO routines printOn and readFrom
*
* Note that operator<< and operator>> are defined at EO level
* using these routines
*/
template< class FitT>
class eoOneMax: public EO<FitT> {
public:
/** Ctor: you MUST provide a default ctor.
* though such individuals will generally be processed
* by some eoInit object
*/
eoOneMax()
{
// START Code of default Ctor of an eoOneMax object
// END Code of default Ctor of an eoOneMax object
}
virtual ~eoOneMax()
{
// START Code of Destructor of an eoEASEAGenome object
// END Code of Destructor of an eoEASEAGenome object
}
virtual string className() const { return "eoOneMax"; }
/** printing... */
void printOn(ostream& _os) const
{
// First write the fitness
EO<FitT>::printOn(_os);
_os << ' ';
// START Code of default output
/** HINTS
* in EO we systematically write the sizes of things before the things
* so readFrom is easier to code (see below)
*/
_os << b.size() << ' ' ;
for (unsigned i=0; i<b.size(); i++)
_os << b[i] << ' ' ;
// END Code of default output
}
/** reading...
* of course, your readFrom must be able to read what printOn writes!!!
*/
void readFrom(istream& _is)
{
// of course you should read the fitness first!
EO<FitT>::readFrom(_is);
// START Code of input
/** HINTS
* remember the eoOneMax object will come from the default ctor
* this is why having the sizes written out is useful
*/
unsigned s;
_is >> s;
b.resize(s);
for (unsigned i=0; i<s; i++)
{
bool bTmp;
_is >> bTmp;
b[i] = bTmp;
}
// END Code of input
}
// accessing and setting values
void setB(vector<bool> & _b)
{
b=_b;
}
const vector<bool> & B()
{
return b;
}
private: // put all data here
// START Private data of an eoOneMax object
std::vector<bool> b;
// END Private data of an eoOneMax object
};
#endif

View file

@ -0,0 +1,68 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for evaluator in EO, a functor that computes the fitness of an EO
==========================================================================
*/
#ifndef _eoOneMaxEvalFunc_h
#define _eoOneMaxEvalFunc_h
// include whatever general include you need
#include <stdexcept>
#include <fstream>
// include the base definition of eoEvalFunc
#include <paradiseo/eo/eoEvalFunc.h>
/**
Always write a comment in this format before class definition
if you want the class to be documented by Doxygen
*/
template <class EOT>
class eoOneMaxEvalFunc : public eoEvalFunc<EOT>
{
public:
/// Ctor - no requirement
// START eventually add or modify the anyVariable argument
eoOneMaxEvalFunc()
// eoOneMaxEvalFunc( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an eoOneMaxEvalFunc object
// END Code of Ctor of an eoOneMaxEvalFunc object
}
/** Actually compute the fitness
*
* @param EOT & _eo the EO object to evaluate
* it should stay templatized to be usable
* with any fitness type
*/
void operator()(EOT & _eo)
{
// test for invalid to avoid recomputing fitness of unmodified individuals
if (_eo.invalid())
{
double fit; // to hold fitness value
// START Code of computation of fitness of the eoOneMax object
const vector<bool> & b = _eo.B();
fit = 0;
for (unsigned i=0; i<b.size(); i++)
fit += (b[i]?0:1);
// END Code of computation of fitness of the eoOneMax object
_eo.fitness(fit);
}
}
private:
// START Private data of an eoOneMaxEvalFunc object
// varType anyVariable; // for example ...
// END Private data of an eoOneMaxEvalFunc object
};
#endif

View file

@ -0,0 +1,62 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for EO objects initialization in EO
============================================
*/
#ifndef _eoOneMaxInit_h
#define _eoOneMaxInit_h
// include the base definition of eoInit
#include <paradiseo/eo/eoInit.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* There is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO (e.g. to initialize
* atoms of an eoVector you will need an eoInit<AtomType>)
*/
template <class GenotypeT>
class eoOneMaxInit: public eoInit<GenotypeT> {
public:
/// Ctor - no requirement
// START eventually add or modify the anyVariable argument
// eoOneMaxInit()
eoOneMaxInit( unsigned _vecSize) : vecSize(_vecSize)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an eoOneMaxInit object
// END Code of Ctor of an eoOneMaxInit object
}
/** initialize a genotype
*
* @param _genotype generally a genotype that has been default-constructed
* whatever it contains will be lost
*/
void operator()(GenotypeT & _genotype)
{
// START Code of random initialization of an eoOneMax object
vector<bool> b(vecSize);
for (unsigned i=0; i<vecSize; i++)
b[i]=rng.flip();
_genotype.setB(b);
// END Code of random initialization of an eoOneMax object
_genotype.invalidate(); // IMPORTANT in case the _genotype is old
}
private:
// START Private data of an eoOneMaxInit object
unsigned vecSize; // size of all bitstrings that this eoInit randomize
// varType anyVariable; // for example ...
// END Private data of an eoOneMaxInit object
};
#endif

View file

@ -0,0 +1,68 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is useful in Emacs-like editors
*/
/*
Template for simple mutation operators
======================================
*/
#ifndef eoOneMaxMutation_H
#define eoOneMaxMutation_H
#include <paradiseo/eo/eoOp.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* THere is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO
*/
template<class GenotypeT>
class eoOneMaxMutation: public eoMonOp<GenotypeT>
{
public:
/**
* Ctor - no requirement
*/
// START eventually add or modify the anyVariable argument
eoOneMaxMutation()
// eoOneMaxMutation( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an eoOneMaxEvalFunc object
// END Code of Ctor of an eoOneMaxEvalFunc object
}
/// The class name. Used to display statistics
string className() const { return "eoOneMaxMutation"; }
/**
* modifies the parent
* @param _genotype The parent genotype (will be modified)
*/
bool operator()(GenotypeT & _genotype)
{
bool isModified(true);
// START code for mutation of the _genotype object
/** Requirement
* if (_genotype has been modified)
* isModified = true;
* else
* isModified = false;
*/
return isModified;
// END code for mutation of the _genotype object
}
private:
// START Private data of an eoOneMaxMutation object
// varType anyVariable; // for example ...
// END Private data of an eoOneMaxMutation object
};
#endif

View file

@ -0,0 +1,70 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for simple quadratic crossover operators
=================================================
Quadratic crossover operators modify the both genotypes
*/
#ifndef eoOneMaxQuadCrossover_H
#define eoOneMaxQuadCrossover_H
#include <paradiseo/eo/eoOp.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* THere is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO
*/
template<class GenotypeT>
class eoOneMaxQuadCrossover: public eoQuadOp<GenotypeT>
{
public:
/**
* Ctor - no requirement
*/
// START eventually add or modify the anyVariable argument
eoOneMaxQuadCrossover()
// eoOneMaxQuadCrossover( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an eoOneMaxEvalFunc object
// END Code of Ctor of an eoOneMaxEvalFunc object
}
/// The class name. Used to display statistics
string className() const { return "eoOneMaxQuadCrossover"; }
/**
* eoQuad crossover - modifies both parents
* @param _genotype1 The first parent
* @param _genotype2 The second parent
*/
bool operator()(GenotypeT& _genotype1, GenotypeT & _genotype2)
{
bool oneAtLeastIsModified(true);
// START code for crossover of _genotype1 and _genotype2 objects
/** Requirement
* if (at least one genotype has been modified) // no way to distinguish
* oneAtLeastIsModified = true;
* else
* oneAtLeastIsModified = false;
*/
return oneAtLeastIsModified;
// END code for crossover of _genotype1 and _genotype2 objects
}
private:
// START Private data of an eoOneMaxQuadCrossover object
// varType anyVariable; // for example ...
// END Private data of an eoOneMaxQuadCrossover object
};
#endif

View file

@ -0,0 +1,128 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
The above line is usefulin Emacs-like editors
*/
/*
Template for creating a new representation in EO
================================================
This is the template file that llows separate compilation of
everything that is representation independant (evolution engine and
general output) for an Evolutionary Algorithm with scalar fitness.
It includes of course the definition of the genotype (eoOneMax.h) and
is written like the make_xxx.cpp files in dirs src/ga (for bitstrings)
and src/es (for real vectors).
*/
// Miscilaneous include and declaration
#include <iostream>
using namespace std;
// eo general include
#include <paradiseo/eo.h>
// the real bounds (not yet in general eo include)
#include <paradiseo/eo/utils/eoRealVectorBounds.h>
// include here whatever specific files for your representation
// Basically, this should include at least the following
/** definition of representation:
* class eoOneMax MUST derive from EO<FitT> for some fitness
*/
#include "eoOneMax.h"
// create an initializer: this is NOT representation-independent
// and will be done in the main file
// However, should you decide to freeze that part, you could use the
// following (and remove it from the main file, of course!!!)
//------------------------------------------------------------------
// #include "make_genotype_OneMax.h"
// eoInit<eoOneMax<double>> & make_genotype(eoParser& _parser, eoState&_state, eoOneMax<double> _eo)
// {
// return do_make_genotype(_parser, _state, _eo);
// }
// eoInit<eoOneMax<eoMinimizingFitness>> & make_genotype(eoParser& _parser, eoState&_state, eoOneMax<eoMinimizingFitness> _eo)
// {
// return do_make_genotype(_parser, _state, _eo);
// }
// same thing for the variation operaotrs
//---------------------------------------
// #include "make_op_OneMax.h"
// eoGenOp<eoOneMax<double>>& make_op(eoParser& _parser, eoState& _state, eoInit<eoOneMax<double>>& _init)
// {
// return do_make_op(_parser, _state, _init);
// }
// eoGenOp<eoOneMax<eoMinimizingFitness>>& make_op(eoParser& _parser, eoState& _state, eoInit<eoOneMax<eoMinimizingFitness>>& _init)
// {
// return do_make_op(_parser, _state, _init);
// }
// The following modules use ***representation independent*** routines
// how to initialize the population
// it IS representation independent if an eoInit is given
#include <paradiseo/eo/do/make_pop.h>
eoPop<eoOneMax<double> >& make_pop(eoParser& _parser, eoState& _state, eoInit<eoOneMax<double> > & _init)
{
return do_make_pop(_parser, _state, _init);
}
eoPop<eoOneMax<eoMinimizingFitness> >& make_pop(eoParser& _parser, eoState& _state, eoInit<eoOneMax<eoMinimizingFitness> > & _init)
{
return do_make_pop(_parser, _state, _init);
}
// the stopping criterion
#include <paradiseo/eo/do/make_continue.h>
eoContinue<eoOneMax<double> >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<eoOneMax<double> > & _eval)
{
return do_make_continue(_parser, _state, _eval);
}
eoContinue<eoOneMax<eoMinimizingFitness> >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<eoOneMax<eoMinimizingFitness> > & _eval)
{
return do_make_continue(_parser, _state, _eval);
}
// outputs (stats, population dumps, ...)
#include <paradiseo/eo/do/make_checkpoint.h>
eoCheckPoint<eoOneMax<double> >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<eoOneMax<double> >& _eval, eoContinue<eoOneMax<double> >& _continue)
{
return do_make_checkpoint(_parser, _state, _eval, _continue);
}
eoCheckPoint<eoOneMax<eoMinimizingFitness> >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<eoOneMax<eoMinimizingFitness> >& _eval, eoContinue<eoOneMax<eoMinimizingFitness> >& _continue)
{
return do_make_checkpoint(_parser, _state, _eval, _continue);
}
// evolution engine (selection and replacement)
#include <paradiseo/eo/do/make_algo_scalar.h>
eoAlgo<eoOneMax<double> >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<eoOneMax<double> >& _eval, eoContinue<eoOneMax<double> >& _continue, eoGenOp<eoOneMax<double> >& _op)
{
return do_make_algo_scalar(_parser, _state, _eval, _continue, _op);
}
eoAlgo<eoOneMax<eoMinimizingFitness> >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<eoOneMax<eoMinimizingFitness> >& _eval, eoContinue<eoOneMax<eoMinimizingFitness> >& _continue, eoGenOp<eoOneMax<eoMinimizingFitness> >& _op)
{
return do_make_algo_scalar(_parser, _state, _eval, _continue, _op);
}
// simple call to the algo. stays there for consistency reasons
// no template for that one
#include <paradiseo/eo/do/make_run.h>
void run_ea(eoAlgo<eoOneMax<double> >& _ga, eoPop<eoOneMax<double> >& _pop)
{
do_run(_ga, _pop);
}
void run_ea(eoAlgo<eoOneMax<eoMinimizingFitness> >& _ga, eoPop<eoOneMax<eoMinimizingFitness> >& _pop)
{
do_run(_ga, _pop);
}

View file

@ -0,0 +1,75 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// make_genotype.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _make_genotype_h
#define _make_genotype_h
#include "eoOneMax.h"
#include "eoOneMaxInit.h"
// also need the parser and param includes
#include <paradiseo/eo/utils/eoParser.h>
#include <paradiseo/eo/utils/eoState.h>
/*
* This fuction does the create an eoInit<eoOneMax>
*
* It could be here tempatized only on the fitness, as it can be used
* to evolve structures with any fitness.
* However, for consistency reasons, it was finally chosen, as in
* the rest of EO, to templatize by the full EOT, as this eventually
* allows to choose the type of genotype at run time (see in es dir)
*
* It returns an eoInit<EOT> that can later be used to initialize
* the population (see make_pop.h).
*
* It uses a parser (to get user parameters) and a state (to store the memory)
* the last argument is to disambiguate the call upon different instanciations.
*
* WARNING: that last argument will generally be the result of calling
* the default ctor of EOT, resulting in most cases in an EOT
* that is ***not properly initialized***
*/
template <class EOT>
eoInit<EOT> & do_make_genotype(eoParameterLoader& _parser, eoState& _state, EOT)
{
// read any useful parameter here from the parser
// the param itself will belong to the parser (as far as memory is concerned)
// paramType & param = _parser.createParam(deafultValue, "Keyword", "Comment to appear in help and status", 'c',"Section of status file").value();
unsigned vecSize = _parser.createParam(unsigned(8), "VecSize", "Size of the bitstrings", 'v',"Representation").value();
// Then built the initializer - a pointer, stored in the eoState
eoInit<EOT>* init = new eoOneMaxInit<EOT>(vecSize);
// store in state
_state.storeFunctor(init);
// and return a reference
return *init;
}
#endif

View file

@ -0,0 +1,210 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// make_op_OneMax.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifndef _make_op_OneMax_h
#define _make_op_OneMax_h
// the operators
#include <paradiseo/eo/eoOp.h>
#include <paradiseo/eo/eoGenOp.h>
#include <paradiseo/eo/eoCloneOps.h>
#include <paradiseo/eo/eoOpContainer.h>
// combinations of simple eoOps (eoMonOp and eoQuadOp)
#include <paradiseo/eo/eoProportionalCombinedOp.h>
/** definition of mutation:
* class eoOneMaxMonop MUST derive from eoMonOp<eoOneMax>
*/
#include "eoOneMaxMutation.h"
/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2):
* class eoOneMaxBinCrossover MUST derive from eoBinOp<eoOneMax>
* OR
* class eoOneMaxQuadCrossover MUST derive from eoQuadOp<eoOneMax>
*/
// #include "../../src/eoOneMaxBinOp.h"
// OR
#include "eoOneMaxQuadCrossover.h"
// also need the parser and state includes
#include <paradiseo/eo/utils/eoParser.h>
#include <paradiseo/eo/utils/eoState.h>
/////////////////// variation operators ///////////////
// canonical (crossover + mutation) only at the moment //
/*
* This function builds the operators that will be applied to the eoOneMax
*
* It uses a parser (to get user parameters), a state (to store the memory)
* the last parameter is an eoInit: if some operator needs some info
* about the genotypes, the init has it all (e.g. bounds, ...)
* Simply do
* EOT myEO;
* _init(myEO);
* and myEO is then an ACTUAL object
*
* As usual, the template is the complete EOT even though only the fitness
* is actually templatized here: the following only applies to eoOneMax
*/
template <class EOT>
eoGenOp<EOT> & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit<EOT>& _init)
{
// this is a temporary version, while Maarten codes the full tree-structured
// general operator input
// BTW we must leave that simple version available somehow, as it is the one
// that 90% people use!
/////////////////////////////
// Variation operators
////////////////////////////
// read crossover and mutations, combine each in a proportional Op
// and create the eoGenOp that calls crossover at rate pCross
// then mutation with rate pMut
// the crossovers
/////////////////
// here we can have eoQuadOp (2->2) only - no time for the eoBinOp case
// you can have more than one - combined in a proportional way
// first, define the crossover objects and read their rates from the parser
// A first crossover
eoQuadOp<Indi> *cross = new eoOneMaxQuadCrossover<Indi> /* (varType _anyVariable) */;
// store in the state
_state.storeFunctor(cross);
// read its relative rate in the combination
double cross1Rate = _parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value();
// and create the combined operator with this one
eoPropCombinedQuadOp<Indi> *propXover =
new eoPropCombinedQuadOp<Indi>(*cross, cross1Rate);
// and of course stor it in the state
_state.storeFunctor(propXover);
// Optional: A second(and third, and ...) crossover
// of course you must create the corresponding classes
// and all ***MUST*** derive from eoQuadOp<Indi>
/* Uncomment if necessary - and replicate as many time as you need
cross = new eoOneMaxSecondCrossover<Indi>(varType _anyVariable);
_state.storeFunctor(cross);
double cross2Rate = _parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value();
propXover.add(*cross, cross2Rate);
*/
// if you want some gentle output, the last one shoudl be like
// propXover.add(*cross, crossXXXRate, true);
// the mutation: same story
////////////////
// you can have more than one - combined in a proportional way
// for each mutation,
// - define the mutator object
// - read its rate from the parser
// - add it to the proportional combination
// a first mutation
eoMonOp<Indi> *mut = new eoOneMaxMutation<Indi>/* (varType _anyVariable) */;
_state.storeFunctor(mut);
// its relative rate in the combination
double mut1Rate = _parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value();
// and the creation of the combined operator with this one
eoPropCombinedMonOp<Indi> *propMutation = new eoPropCombinedMonOp<Indi>(*mut, mut1Rate);
_state.storeFunctor(propMutation);
// Optional: A second(and third, and ...) mutation with their rates
// of course you must create the corresponding classes
// and all ***MUST*** derive from eoMonOp<Indi>
/* Uncomment if necessary - and replicate as many time as you need
mut = new eoOneMaxSecondMutation<Indi>(varType _anyVariable);
_state.storeFunctor(mut);
double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value();
propMutation.add(*mut, mut2Rate);
*/
// if you want some gentle output, the last one shoudl be like
// propMutation.add(*mut, mutXXXRate, true);
// end of crossover and mutation definitions
////////////////////////////////////////////
// END Modify definitions of objects by eventually add parameters
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// from now on, you do not need to modify anything
// though you CAN add things to the checkpointing (see tutorial)
// now build the eoGenOp:
// to simulate SGA (crossover with proba pCross + mutation with proba pMut
// we must construct
// a sequential combination of
// with proba 1, a proportional combination of
// a QuadCopy and our crossover
// with proba pMut, our mutation
// but of course you're free to use any smart combination you could think of
// especially, if you have to use eoBinOp rather than eoQuad Op youùll have
// to modify that part
// First read the individual level parameters
eoValueParam<double>& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" );
// minimum check
if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) )
throw runtime_error("Invalid pCross");
eoValueParam<double>& pMutParam = _parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" );
// minimum check
if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) )
throw runtime_error("Invalid pMut");
// the crossover - with probability pCross
eoProportionalOp<Indi> * propOp = new eoProportionalOp<Indi> ;
_state.storeFunctor(propOp);
eoQuadOp<Indi> *ptQuad = new eoQuadCloneOp<Indi>;
_state.storeFunctor(ptQuad);
propOp->add(*propXover, pCrossParam.value()); // crossover, with proba pcross
propOp->add(*ptQuad, 1-pCrossParam.value()); // nothing, with proba 1-pcross
// now the sequential
eoSequentialOp<Indi> *op = new eoSequentialOp<Indi>;
_state.storeFunctor(op);
op->add(*propOp, 1.0); // always do combined crossover
op->add(*propMutation, pMutParam.value()); // then mutation, with proba pmut
// that's it - return a reference
return *op;
}
#endif

182
tutorial/eo/Lesson6/BinaryPSO.cpp Executable file
View file

@ -0,0 +1,182 @@
//-----------------------------------------------------------------------------
// BinaryPSO.cpp
//-----------------------------------------------------------------------------
//*
// An instance of a VERY simple Real-coded binary Particle Swarm Optimization Algorithm
//
//-----------------------------------------------------------------------------
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <paradiseo/eo.h>
// Use functions from namespace std
using namespace std;
//-----------------------------------------------------------------------------
typedef eoMinimizingFitness FitT;
typedef eoBitParticle < FitT > Particle;
//-----------------------------------------------------------------------------
// EVALFUNC
//-----------------------------------------------------------------------------
// Just a simple function that takes binary value of a chromosome and sets
// the fitness
double binary_value (const Particle & _particle)
{
double sum = 0;
for (unsigned i = 0; i < _particle.size(); i++)
sum +=_particle[i];
return (sum);
}
void main_function(int argc, char **argv)
{
// PARAMETRES
// all parameters are hard-coded!
const unsigned int SEED = 42; // seed for random number generator
const unsigned int MAX_GEN=500;
const unsigned int VEC_SIZE = 10;
const unsigned int POP_SIZE = 20;
const unsigned int NEIGHBORHOOD_SIZE= 3;
const double VELOCITY_INIT_MIN= -1;
const double VELOCITY_INIT_MAX= 1;
const double VELOCITY_MIN= -1.5;
const double VELOCITY_MAX= 1.5;
const double INERTIA= 1;
const double LEARNING_FACTOR1= 1.7;
const double LEARNING_FACTOR2= 2.3;
//////////////////////////
// RANDOM SEED
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
/// SWARM
// population <=> swarm
eoPop<Particle> pop;
/// EVALUATION
// Evaluation: from a plain C++ fn to an EvalFunc Object
eoEvalFuncPtr<Particle, double, const Particle& > eval( binary_value );
///////////////
/// TOPOLOGY
//////////////
// ring topology
eoRingTopology<Particle> topology(NEIGHBORHOOD_SIZE);
/////////////////////
// INITIALIZATION
////////////////////
// position initialization
eoUniformGenerator<bool> uGen;
eoInitFixedLength < Particle > random (VEC_SIZE, uGen);
pop.append (POP_SIZE, random);
// velocities initialization component
eoUniformGenerator < double >sGen (VELOCITY_INIT_MIN, VELOCITY_INIT_MAX);
eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen);
// first best position initialization component
eoFirstIsBestInit < Particle > localInit;
// Create an eoInitialier that:
// - performs a first evaluation of the particles
// - initializes the velocities
// - the first best positions of each particle
// - setups the topology
eoInitializer <Particle> fullInit(eval,veloRandom,localInit,topology,pop);
// Full initialization here to be able to print the initial population
// Else: give the "init" component in the eoEasyPSO constructor
fullInit();
/////////////
// OUTPUT
////////////
// sort pop before printing it!
pop.sort();
// Print (sorted) the initial population (raw printout)
cout << "INITIAL POPULATION:" << endl;
for (unsigned i = 0; i < pop.size(); ++i)
cout << "\t best fit=" << pop[i] << endl;
///////////////
/// VELOCITY
//////////////
// Create the bounds for the velocity not go to far away
eoRealVectorBounds bnds(VEC_SIZE,VELOCITY_MIN,VELOCITY_MAX);
// the velocity itself that needs the topology and a few constants
eoStandardVelocity <Particle> velocity (topology,INERTIA,LEARNING_FACTOR1,LEARNING_FACTOR2,bnds);
///////////////
/// FLIGHT
//////////////
// Binary flight based on sigmoid function
eoSigBinaryFlight <Particle> flight;
////////////////////////
/// STOPPING CRITERIA
///////////////////////
// the algo will run for MAX_GEN iterations
eoGenContinue <Particle> genCont (MAX_GEN);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// standard PSO requires
// stopping criteria, evaluation,velocity, flight
eoEasyPSO<Particle> pso(genCont, eval, velocity, flight);
// Apply the algo to the swarm - that's it!
pso(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL POPULATION:" << endl;
for (unsigned i = 0; i < pop.size(); ++i)
cout << "\t best fit=" << pop[i] << endl;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,51 @@
######################################################################################
### 1) Include the sources
######################################################################################
#include_directories(${EO_SRC_DIR}/src)
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
if(NOT WIN32 OR CYGWIN)
link_directories(${EO_BIN_DIR}/lib)
endif(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
if(WIN32 AND NOT CYGWIN)
link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE})
endif(WIN32 AND NOT CYGWIN)
######################################################################################
### 3) Define your targets
######################################################################################
add_executable(BinaryPSO BinaryPSO.cpp)
add_executable(RealPSO RealPSO.cpp)
######################################################################################
### 4) Optionnal
######################################################################################
set(BINARYPSO_VERSION ${GLOBAL_VERSION})
set_target_properties(BinaryPSO PROPERTIES VERSION "${BINARYPSO_VERSION}")
set(REALPSO_VERSION ${GLOBAL_VERSION})
set_target_properties(RealPSO PROPERTIES VERSION "${REALPSO_VERSION}")
######################################################################################
### 5) Link the librairies for the targets
######################################################################################
target_link_libraries(BinaryPSO eo eoutils)
target_link_libraries(RealPSO eo eoutils)
######################################################################################
### 6) Configure project installation paths
######################################################################################
install(TARGETS BinaryPSO RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson6 COMPONENT examples)
install(TARGETS RealPSO RUNTIME DESTINATION share/${PROJECT_TAG}/eo/examples/Lesson6 COMPONENT examples)
######################################################################################

View file

@ -0,0 +1,31 @@
### This Makefile is part of the tutorial of the EO library
# Unlike other Makefiles in EO, it is not using the automake/autoconf
# so that it stays easy to understant (you are in the tutorial, remember!)
# MS, Oct. 2002
# if you use this Makefile as a starting point for another application
# you might need to modify the following
DIR_EO = ../../src
.SUFFIXES: .cpp
# Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++
# However, if you are using this Makefile within xemacs,
# and have problems with the interpretation of the output (and its colors)
# then you should use c++ instead (make CXX=c++ will do)
.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp
#$(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a
.cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp
PSO = BinaryPSO RealPSO
ALL = $(PSO)
lesson6 : $(PSO)
all : $(ALL)
clean :
@/bin/rm $(ALL) *.o *.sav *.xg *.status *~

183
tutorial/eo/Lesson6/RealPSO.cpp Executable file
View file

@ -0,0 +1,183 @@
//-----------------------------------------------------------------------------
// RealPSO.cpp
//-----------------------------------------------------------------------------
//*
// An instance of a VERY simple Real-coded Particle Swarm Optimization Algorithm
//
//-----------------------------------------------------------------------------
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <paradiseo/eo.h>
// Use functions from namespace std
using namespace std;
//-----------------------------------------------------------------------------
typedef eoMinimizingFitness FitT;
typedef eoRealParticle < FitT > Particle;
//-----------------------------------------------------------------------------
// EVALFUNC
//-----------------------------------------------------------------------------
// a simple fitness function that computes the euclidian norm of a real vector
FitT real_value (const Particle & _particle)
{
double sum = 0;
for (unsigned i = 0; i < _particle.size(); i++)
sum += pow(_particle[i],2);
return (sqrt(sum));
}
void main_function(int argc, char **argv)
{
// PARAMETRES
// all parameters are hard-coded!
const unsigned int SEED = 42; // seed for random number generator
const unsigned int MAX_GEN=100;
const unsigned int VEC_SIZE = 2;
const unsigned int POP_SIZE = 20;
const unsigned int NEIGHBORHOOD_SIZE= 5;
const double POS_INIT_MIN= -2;
const double POS_INIT_MAX= 2;
const double VELOCITY_INIT_MIN= -1;
const double VELOCITY_INIT_MAX= 1;
const double VELOCITY_MIN= -1.5;
const double VELOCITY_MAX= 1.5;
const double INERTIA= 1;
const double LEARNING_FACTOR1= 1.7;
const double LEARNING_FACTOR2= 2.3;
//////////////////////////
// RANDOM SEED
//////////////////////////
//reproducible random seed: if you don't change SEED above,
// you'll aways get the same result, NOT a random run
rng.reseed(SEED);
/// SWARM
// population <=> swarm
eoPop<Particle> pop;
/// EVALUATION
// Evaluation: from a plain C++ fn to an EvalFunc Object
eoEvalFuncPtr<Particle, FitT, const Particle& > eval( real_value );
///////////////
/// TOPOLOGY
//////////////
// linear topology
eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE);
/////////////////////
// INITIALIZATION
////////////////////
// position initialization
eoUniformGenerator < double >uGen (POS_INIT_MIN, POS_INIT_MAX);
eoInitFixedLength < Particle > random (VEC_SIZE, uGen);
pop.append (POP_SIZE, random);
// velocities initialization component
eoUniformGenerator < double >sGen (VELOCITY_INIT_MIN, VELOCITY_INIT_MAX);
eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen);
// first best position initialization component
eoFirstIsBestInit < Particle > localInit;
// Create an eoInitialier that:
// - performs a first evaluation of the particles
// - initializes the velocities
// - the first best positions of each particle
// - setups the topology
eoInitializer <Particle> fullInit(eval,veloRandom,localInit,topology,pop);
// Full initialization here to be able to print the initial population
// Else: give the "init" component in the eoEasyPSO constructor
fullInit();
/////////////
// OUTPUT
////////////
// sort pop before printing it!
pop.sort();
// Print (sorted) the initial population (raw printout)
cout << "INITIAL POPULATION:" << endl;
for (unsigned i = 0; i < pop.size(); ++i)
cout << "\t best fit=" << pop[i] << endl;
///////////////
/// VELOCITY
//////////////
// Create the bounds for the velocity not go to far away
eoRealVectorBounds bnds(VEC_SIZE,VELOCITY_MIN,VELOCITY_MAX);
// the velocity itself that needs the topology and a few constants
eoStandardVelocity <Particle> velocity (topology,INERTIA,LEARNING_FACTOR1,LEARNING_FACTOR2,bnds);
///////////////
/// FLIGHT
//////////////
// flight
eoStandardFlight <Particle> flight;
////////////////////////
/// STOPPING CRITERIA
///////////////////////
// the algo will run for MAX_GEN iterations
eoGenContinue <Particle> genCont (MAX_GEN);
// GENERATION
/////////////////////////////////////////
// the algorithm
////////////////////////////////////////
// standard PSO requires
// stopping criteria, evaluation,velocity, flight
eoEasyPSO<Particle> pso(genCont, eval, velocity, flight);
// Apply the algo to the swarm - that's it!
pso(pop);
// OUTPUT
// Print (sorted) intial population
pop.sort();
cout << "FINAL POPULATION:" << endl;
for (unsigned i = 0; i < pop.size(); ++i)
cout << "\t best fit=" << pop[i] << endl;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << '\n';
}
return 1;
}
//-----------------------------------------------------------------------------

32
tutorial/eo/Makefile.simple Executable file
View file

@ -0,0 +1,32 @@
SUBDIRS = Lesson1 Lesson2 Lesson3 Lesson4 Lesson5 Lesson6
all:
for i in $(SUBDIRS); do cd $$i && $(MAKE) all; cd ..; done
lesson1 :
cd Lesson1; make
lesson2 :
cd Lesson2; make
lesson3 :
cd Lesson3; make
lesson4 :
cd Lesson4; make
lesson5 :
cd Lesson5; make
lesson6 :
cd Lesson6; make
#empty dist and distdir to let top-level 'make' do its job
dist :
distdir :
check :
clean:
for i in $(SUBDIRS); do cd $$i && $(MAKE) clean; cd ..; done

View file

@ -0,0 +1,63 @@
How to install EoMPI
====================
Install OpenMpi
---------------
1) Download OpenMPI on their website or with the following command:
wget http://www.open-mpi.org/software/ompi/v1.6/downloads/openmpi-1.6.tar.bz2
2) Untar the downloaded archive in a directory and change working directory to there:
tar -xvjf openmpi*.tar.bz2
cd openmpi-X.Y
3) Use configuration script to indicate in which directory OpenMPI should be installed, and other options:
Simplest configuration:
./configure --prefix=/home/`whoami`/openmpi/
Only static libraries:
./configure --enable-static --disable-shared
Only static libraries, with prefix, disable build for Fortran77 and Fortran90, add support for SGE:
./configure --enable-static --disable-shared --prefix=/home/`whoami`/openmpi/ --disable-mpi-f77 --disable-mpi-f90 --with-sge
Other options are available in the README file.
4) Make it and install:
In sequential:
make all install
Or in parallel:
make -j 2 all
make install
5) Try to compile and run the sample program:
~/openmpi/bin/mpicxx -o sample mpi.c
~/openmpi/bin/mpirun -np 3 ./sample
Configure EO to use MPI
-----------------------
You only need to configure eo-conf.cmake so as to use MPI :
1) Put the WITH_MPI boolean to true:
SET(WITH_MPI TRUE CACHE BOOL "Use mpi ?" FORCE)
2) Indicate in which directories you have installed openmpi:
SET(MPI_DIR "/where/did/you/install/openmpi" CACHE PATH "OpenMPI directory" FORCE)
3) Recompile eo:
./distclean
./build_gcc_linux_release.sh
4) If you meet any issue, don't hesitate to contact the EO mailing list:
eodev-main@lists.sourceforge.net

View file

@ -0,0 +1,405 @@
html {
height: 100%;
}
body.deck-container {
overflow-y: auto;
position: static;
}
.deck-container {
position: relative;
min-height: 100%;
margin: 0 auto;
padding: 0 48px;
font-size: 16px;
line-height: 1.25;
overflow: hidden;
/* Resets and base styles from HTML5 Boilerplate */
/* End HTML5 Boilerplate adaptations */
}
.js .deck-container {
visibility: hidden;
}
.ready .deck-container {
visibility: visible;
}
.touch .deck-container {
-webkit-text-size-adjust: none;
-moz-text-size-adjust: none;
}
.deck-container div, .deck-container span, .deck-container object, .deck-container iframe,
.deck-container h1, .deck-container h2, .deck-container h3, .deck-container h4, .deck-container h5, .deck-container h6, .deck-container p, .deck-container blockquote, .deck-container pre,
.deck-container abbr, .deck-container address, .deck-container cite, .deck-container code, .deck-container del, .deck-container dfn, .deck-container em, .deck-container img, .deck-container ins, .deck-container kbd, .deck-container q, .deck-container samp,
.deck-container small, .deck-container strong, .deck-container sub, .deck-container sup, .deck-container var, .deck-container b, .deck-container i, .deck-container dl, .deck-container dt, .deck-container dd, .deck-container ol, .deck-container ul, .deck-container li,
.deck-container fieldset, .deck-container form, .deck-container label, .deck-container legend,
.deck-container table, .deck-container caption, .deck-container tbody, .deck-container tfoot, .deck-container thead, .deck-container tr, .deck-container th, .deck-container td,
.deck-container article, .deck-container aside, .deck-container canvas, .deck-container details, .deck-container figcaption, .deck-container figure,
.deck-container footer, .deck-container header, .deck-container hgroup, .deck-container menu, .deck-container nav, .deck-container section, .deck-container summary,
.deck-container time, .deck-container mark, .deck-container audio, .deck-container video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.deck-container article, .deck-container aside, .deck-container details, .deck-container figcaption, .deck-container figure,
.deck-container footer, .deck-container header, .deck-container hgroup, .deck-container menu, .deck-container nav, .deck-container section {
display: block;
}
.deck-container blockquote, .deck-container q {
quotes: none;
}
.deck-container blockquote:before, .deck-container blockquote:after, .deck-container q:before, .deck-container q:after {
content: "";
content: none;
}
.deck-container ins {
background-color: #ff9;
color: #000;
text-decoration: none;
}
.deck-container mark {
background-color: #ff9;
color: #000;
font-style: italic;
font-weight: bold;
}
.deck-container del {
text-decoration: line-through;
}
.deck-container abbr[title], .deck-container dfn[title] {
border-bottom: 1px dotted;
cursor: help;
}
.deck-container table {
border-collapse: collapse;
border-spacing: 0;
}
.deck-container hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
.deck-container input, .deck-container select {
vertical-align: middle;
}
.deck-container select, .deck-container input, .deck-container textarea, .deck-container button {
font: 99% sans-serif;
}
.deck-container pre, .deck-container code, .deck-container kbd, .deck-container samp {
font-family: monospace, sans-serif;
}
.deck-container a {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.deck-container a:hover, .deck-container a:active {
outline: none;
}
.deck-container ul, .deck-container ol {
margin-left: 2em;
vertical-align: top;
}
.deck-container ol {
list-style-type: decimal;
}
.deck-container nav ul, .deck-container nav li {
margin: 0;
list-style: none;
list-style-image: none;
}
.deck-container small {
font-size: 85%;
}
.deck-container strong, .deck-container th {
font-weight: bold;
}
.deck-container td {
vertical-align: top;
}
.deck-container sub, .deck-container sup {
font-size: 75%;
line-height: 0;
position: relative;
}
.deck-container sup {
top: -0.5em;
}
.deck-container sub {
bottom: -0.25em;
}
.deck-container textarea {
overflow: auto;
}
.ie6 .deck-container legend, .ie7 .deck-container legend {
margin-left: -7px;
}
.deck-container input[type="radio"] {
vertical-align: text-bottom;
}
.deck-container input[type="checkbox"] {
vertical-align: bottom;
}
.ie7 .deck-container input[type="checkbox"] {
vertical-align: baseline;
}
.ie6 .deck-container input {
vertical-align: text-bottom;
}
.deck-container label, .deck-container input[type="button"], .deck-container input[type="submit"], .deck-container input[type="image"], .deck-container button {
cursor: pointer;
}
.deck-container button, .deck-container input, .deck-container select, .deck-container textarea {
margin: 0;
}
.deck-container input:invalid, .deck-container textarea:invalid {
border-radius: 1px;
-moz-box-shadow: 0px 0px 5px red;
-webkit-box-shadow: 0px 0px 5px red;
box-shadow: 0px 0px 5px red;
}
.deck-container input:invalid .no-boxshadow, .deck-container textarea:invalid .no-boxshadow {
background-color: #f0dddd;
}
.deck-container button {
width: auto;
overflow: visible;
}
.ie7 .deck-container img {
-ms-interpolation-mode: bicubic;
}
.deck-container, .deck-container select, .deck-container input, .deck-container textarea {
color: #444;
}
.deck-container a {
color: #607890;
}
.deck-container a:hover, .deck-container a:focus {
color: #036;
}
.deck-container a:link {
-webkit-tap-highlight-color: #fff;
}
.deck-container.deck-loading {
display: none;
}
.slide {
width: auto;
min-height: 100%;
position: relative;
}
.slide h1 {
font-size: 4.5em;
}
.slide h1, .slide .vcenter {
font-weight: bold;
text-align: center;
padding-top: 1em;
max-height: 100%;
}
.csstransforms .slide h1, .csstransforms .slide .vcenter {
padding: 0 48px;
position: absolute;
left: 0;
right: 0;
top: 50%;
-webkit-transform: translate(0, -50%);
-moz-transform: translate(0, -50%);
-ms-transform: translate(0, -50%);
-o-transform: translate(0, -50%);
transform: translate(0, -50%);
}
.slide .vcenter h1 {
position: relative;
top: auto;
padding: 0;
-webkit-transform: none;
-moz-transform: none;
-ms-transform: none;
-o-transform: none;
transform: none;
}
.slide h2 {
font-size: 2.25em;
font-weight: bold;
padding-top: .5em;
margin: 0 0 .66666em 0;
border-bottom: 3px solid #888;
}
.slide h3 {
font-size: 1.4375em;
font-weight: bold;
margin-bottom: .30435em;
}
.slide h4 {
font-size: 1.25em;
font-weight: bold;
margin-bottom: .25em;
}
.slide h5 {
font-size: 1.125em;
font-weight: bold;
margin-bottom: .2222em;
}
.slide h6 {
font-size: 1em;
font-weight: bold;
}
.slide img, .slide iframe, .slide video {
display: block;
max-width: 100%;
}
.slide video, .slide iframe, .slide img {
display: block;
margin: 0 auto;
}
.slide p, .slide blockquote, .slide iframe, .slide img, .slide ul, .slide ol, .slide pre, .slide video {
margin-bottom: 1em;
}
.slide pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
padding: 1em;
border: 1px solid #888;
}
.slide em {
font-style: italic;
}
.slide li {
padding: .25em 0;
vertical-align: middle;
}
.deck-before, .deck-previous, .deck-next, .deck-after {
position: absolute;
left: -999em;
top: -999em;
}
.deck-current {
z-index: 2;
}
.slide .slide {
visibility: hidden;
position: static;
min-height: 0;
}
.deck-child-current {
position: static;
z-index: 2;
}
.deck-child-current .slide {
visibility: hidden;
}
.deck-child-current .deck-previous, .deck-child-current .deck-before, .deck-child-current .deck-current {
visibility: visible;
}
@media screen and (max-device-width: 480px) {
/* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */
}
@media print {
* {
background: transparent !important;
color: black !important;
text-shadow: none !important;
filter: none !important;
-ms-filter: none !important;
-webkit-box-reflect: none !important;
-moz-box-reflect: none !important;
-webkit-box-shadow: none !important;
-moz-box-shadow: none !important;
box-shadow: none !important;
}
* :before, * :after {
display: none !important;
}
a, a:visited {
color: #444 !important;
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
.ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after {
content: "";
}
pre, blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr, img {
page-break-inside: avoid;
}
@page {
margin: 0.5cm;
}
p, h2, h3 {
orphans: 3;
widows: 3;
}
h2, h3 {
page-break-after: avoid;
}
.slide {
position: static !important;
visibility: visible !important;
display: block !important;
-webkit-transform: none !important;
-moz-transform: none !important;
-o-transform: none !important;
-ms-transform: none !important;
transform: none !important;
opacity: 1 !important;
}
h1, .vcenter {
-webkit-transform: none !important;
-moz-transform: none !important;
-o-transform: none !important;
-ms-transform: none !important;
transform: none !important;
padding: 0 !important;
position: static !important;
}
.deck-container > .slide {
page-break-after: always;
}
.deck-container {
width: 100% !important;
height: auto !important;
padding: 0 !important;
display: block !important;
}
script {
display: none;
}
}

View file

@ -0,0 +1,41 @@
.deck-container .goto-form {
position: absolute;
z-index: 3;
bottom: 10px;
left: 50%;
height: 1.75em;
margin: 0 0 0 -9.125em;
line-height: 1.75em;
padding: 0.625em;
display: none;
background: #ccc;
overflow: hidden;
}
.borderradius .deck-container .goto-form {
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}
.deck-container .goto-form label {
font-weight: bold;
}
.deck-container .goto-form label, .deck-container .goto-form input {
display: inline-block;
font-family: inherit;
}
.deck-goto .goto-form {
display: block;
}
#goto-slide {
width: 8.375em;
margin: 0 0.625em;
height: 1.4375em;
}
@media print {
.goto-form, #goto-slide {
display: none !important;
}
}

View file

@ -0,0 +1,13 @@
.deck-container .deck-permalink {
display: none;
position: absolute;
z-index: 4;
bottom: 30px;
right: 0;
width: 48px;
text-align: center;
}
.no-history .deck-container:hover .deck-permalink {
display: block;
}

View file

@ -0,0 +1,47 @@
.deck-menu .slide {
background: #eee;
position: relative;
left: 0;
top: 0;
visibility: visible;
cursor: pointer;
}
.no-csstransforms .deck-menu > .slide {
float: left;
width: 22%;
height: 22%;
min-height: 0;
margin: 1%;
font-size: 0.22em;
overflow: hidden;
padding: 0 0.5%;
}
.csstransforms .deck-menu > .slide {
-webkit-transform: scale(0.22) !important;
-moz-transform: scale(0.22) !important;
-o-transform: scale(0.22) !important;
-ms-transform: scale(0.22) !important;
transform: scale(0.22) !important;
-webkit-transform-origin: 0 0;
-moz-transform-origin: 0 0;
-o-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
height: 100%;
overflow: hidden;
padding: 0 48px;
margin: 12px;
}
.deck-menu iframe, .deck-menu img, .deck-menu video {
max-width: 100%;
}
.deck-menu .deck-current, .no-touch .deck-menu .slide:hover {
background: #ddf;
}
.deck-menu.deck-container:hover .deck-prev-link, .deck-menu.deck-container:hover .deck-next-link {
display: none;
}

View file

@ -0,0 +1,43 @@
.deck-container .deck-prev-link, .deck-container .deck-next-link {
display: none;
position: absolute;
z-index: 3;
top: 50%;
width: 32px;
height: 32px;
margin-top: -16px;
font-size: 20px;
font-weight: bold;
line-height: 32px;
vertical-align: middle;
text-align: center;
text-decoration: none;
color: #fff;
background: #888;
}
.borderradius .deck-container .deck-prev-link, .borderradius .deck-container .deck-next-link {
-webkit-border-radius: 16px;
-moz-border-radius: 16px;
border-radius: 16px;
}
.deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-prev-link:active, .deck-container .deck-prev-link:visited, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus, .deck-container .deck-next-link:active, .deck-container .deck-next-link:visited {
color: #fff;
}
.deck-container .deck-prev-link {
left: 8px;
}
.deck-container .deck-next-link {
right: 8px;
}
.deck-container:hover .deck-prev-link, .deck-container:hover .deck-next-link {
display: block;
}
.deck-container:hover .deck-prev-link.deck-nav-disabled, .touch .deck-container:hover .deck-prev-link, .deck-container:hover .deck-next-link.deck-nav-disabled, .touch .deck-container:hover .deck-next-link {
display: none;
}
@media print {
.deck-prev-link, .deck-next-link {
display: none !important;
}
}

View file

@ -0,0 +1,28 @@
/* Remove this line if you are embedding deck.js in a page and
using the scale extension. */
.csstransforms {
overflow: hidden;
}
.csstransforms .deck-container.deck-scale:not(.deck-menu) > .slide {
-webkit-box-sizing: padding-box;
-moz-box-sizing: padding-box;
box-sizing: padding-box;
width: 100%;
padding-bottom: 20px;
}
.csstransforms .deck-container.deck-scale:not(.deck-menu) > .slide > .deck-slide-scaler {
-webkit-transform-origin: 50% 0;
-moz-transform-origin: 50% 0;
-o-transform-origin: 50% 0;
-ms-transform-origin: 50% 0;
transform-origin: 50% 0;
}
.csstransforms .deck-container.deck-menu .deck-slide-scaler {
-webkit-transform: none !important;
-moz-transform: none !important;
-o-transform: none !important;
-ms-transform: none !important;
transform: none !important;
}

View file

@ -0,0 +1,18 @@
.deck-container .deck-status {
position: absolute;
bottom: 10px;
right: 5px;
color: #888;
z-index: 3;
margin: 0;
}
body.deck-container .deck-status {
position: fixed;
}
@media print {
.deck-status {
display: none;
}
}

View file

@ -0,0 +1,9 @@
.changed
{
color: green;
}
.specific
{
color: red;
}

View file

@ -0,0 +1,76 @@
.csstransitions.csstransforms {
overflow-x: hidden;
}
.csstransitions.csstransforms .deck-container > .slide {
-webkit-transition: -webkit-transform 500ms ease-in-out;
-moz-transition: -moz-transform 500ms ease-in-out;
-ms-transition: -ms-transform 500ms ease-in-out;
-o-transition: -o-transform 500ms ease-in-out;
transition: transform 500ms ease-in-out;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide {
position: absolute;
top: 0;
left: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
padding: 0 48px;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .slide {
position: relative;
left: 0;
top: 0;
-webkit-transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out;
-moz-transition: -moz-transform 500ms ease-in-out, opacity 500ms ease-in-out;
-ms-transition: -ms-transform 500ms ease-in-out, opacity 500ms ease-in-out;
-o-transition: -o-transform 500ms ease-in-out, opacity 500ms ease-in-out;
transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-next, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-after {
visibility: visible;
-webkit-transform: translate3d(200%, 0, 0);
-moz-transform: translate(200%, 0);
-ms-transform: translate(200%, 0);
-o-transform: translate(200%, 0);
transform: translate3d(200%, 0, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous {
-webkit-transform: translate3d(-200%, 0, 0);
-moz-transform: translate(-200%, 0);
-ms-transform: translate(-200%, 0);
-o-transform: translate(-200%, 0);
transform: translate3d(-200%, 0, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before {
-webkit-transform: translate3d(-400%, 0, 0);
-moz-transform: translate(-400%, 0);
-ms-transform: translate(-400%, 0);
-o-transform: translate(-400%, 0);
transform: translate3d(-400%, 0, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-next {
-webkit-transform: translate3d(200%, 0, 0);
-moz-transform: translate(200%, 0);
-ms-transform: translate(200%, 0);
-o-transform: translate(200%, 0);
transform: translate3d(200%, 0, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-after {
-webkit-transform: translate3d(400%, 0, 0);
-moz-transform: translate(400%, 0);
-ms-transform: translate(400%, 0);
-o-transform: translate(400%, 0);
transform: translate3d(400%, 0, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before .slide, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous .slide {
visibility: visible;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-child-current {
-webkit-transform: none;
-moz-transform: none;
-ms-transform: none;
-o-transform: none;
transform: none;
}

View file

@ -0,0 +1,67 @@
pre.sh_sourceCode {
background-color: white;
color: black;
font-style: normal;
font-weight: normal;
}
pre.sh_sourceCode .sh_keyword { color: blue; font-weight: bold; } /* language keywords */
pre.sh_sourceCode .sh_type { color: darkgreen; } /* basic types */
pre.sh_sourceCode .sh_usertype { color: teal; } /* user defined types */
pre.sh_sourceCode .sh_string { color: red; font-family: monospace; } /* strings and chars */
pre.sh_sourceCode .sh_regexp { color: orange; font-family: monospace; } /* regular expressions */
pre.sh_sourceCode .sh_specialchar { color: pink; font-family: monospace; } /* e.g., \n, \t, \\ */
pre.sh_sourceCode .sh_comment { color: brown; font-style: italic; } /* comments */
pre.sh_sourceCode .sh_number { color: purple; } /* literal numbers */
pre.sh_sourceCode .sh_preproc { color: darkblue; font-weight: bold; } /* e.g., #include, import */
pre.sh_sourceCode .sh_symbol { color: darkred; } /* e.g., <, >, + */
pre.sh_sourceCode .sh_function { color: black; font-weight: bold; } /* function calls and declarations */
pre.sh_sourceCode .sh_cbracket { color: red; } /* block brackets (e.g., {, }) */
pre.sh_sourceCode .sh_todo { font-weight: bold; background-color: cyan; } /* TODO and FIXME */
/* Predefined variables and functions (for instance glsl) */
pre.sh_sourceCode .sh_predef_var { color: darkblue; }
pre.sh_sourceCode .sh_predef_func { color: darkblue; font-weight: bold; }
/* for OOP */
pre.sh_sourceCode .sh_classname { color: teal; }
/* line numbers (not yet implemented) */
pre.sh_sourceCode .sh_linenum { color: black; font-family: monospace; }
/* Internet related */
pre.sh_sourceCode .sh_url { color: blue; text-decoration: underline; font-family: monospace; }
/* for ChangeLog and Log files */
pre.sh_sourceCode .sh_date { color: blue; font-weight: bold; }
pre.sh_sourceCode .sh_time, pre.sh_sourceCode .sh_file { color: darkblue; font-weight: bold; }
pre.sh_sourceCode .sh_ip, pre.sh_sourceCode .sh_name { color: darkgreen; }
/* for Prolog, Perl... */
pre.sh_sourceCode .sh_variable { color: darkgreen; }
/* for LaTeX */
pre.sh_sourceCode .sh_italics { color: darkgreen; font-style: italic; }
pre.sh_sourceCode .sh_bold { color: darkgreen; font-weight: bold; }
pre.sh_sourceCode .sh_underline { color: darkgreen; text-decoration: underline; }
pre.sh_sourceCode .sh_fixed { color: green; font-family: monospace; }
pre.sh_sourceCode .sh_argument { color: darkgreen; }
pre.sh_sourceCode .sh_optionalargument { color: purple; }
pre.sh_sourceCode .sh_math { color: orange; }
pre.sh_sourceCode .sh_bibtex { color: blue; }
/* for diffs */
pre.sh_sourceCode .sh_oldfile { color: orange; }
pre.sh_sourceCode .sh_newfile { color: darkgreen; }
pre.sh_sourceCode .sh_difflines { color: blue; }
/* for css */
pre.sh_sourceCode .sh_selector { color: purple; }
pre.sh_sourceCode .sh_property { color: blue; }
pre.sh_sourceCode .sh_value { color: darkgreen; font-style: italic; }
/* other */
pre.sh_sourceCode .sh_section { color: black; font-weight: bold; }
pre.sh_sourceCode .sh_paren { color: red; }
pre.sh_sourceCode .sh_attribute { color: darkgreen; }

View file

@ -0,0 +1,91 @@
.deck-container em {
color:rgb(255,115,0);
}
.deck-container s {
color:rgb(180,180,211);
}
.deck-container {
font-family: "Helvetica Neue", sans-serif;
font-size: 1.75em;
color:RGB(50,50,101);
background:white url("./img/thales.jpg") no-repeat fixed bottom left;
}
.deck-container .slide {
}
.deck-container .slide h1 {
color:rgb(50,50,101);
}
.deck-container .slide h2 {
color:rgb(255,115,0);
border-bottom-color:lightgray;
}
.deck-container .slide h3 {
color:RGB(57,138,199);
}
.deck-container .slide pre {
border-color: #ccc;
}
.deck-container .slide blockquote {
font-size: 2em;
font-style: italic;
padding: 1em 2em;
color: #000;
border-left: 5px solid #ccc;
font-family:serif;
}
.deck-container .slide blockquote p {
margin: 0;
}
.deck-container .slide blockquote cite {
font-size: .5em;
font-style: normal;
font-weight: bold;
color: #888;
}
.deck-container .slide ::-moz-selection {
background: #c00;
color: #fff;
}
.deck-container .slide ::selection {
background: #c00;
color: #fff;
}
.deck-container .slide a, .deck-container .slide a:hover, .deck-container .slide a:focus, .deck-container .slide a:active, .deck-container .slide a:visited {
color:RGB(152,191,12);
text-decoration: none;
}
.deck-container .slide a:hover, .deck-container .slide a:focus {
text-decoration: underline;
}
.deck-container > .slide .deck-before, .deck-container > .slide .deck-previous {
opacity: 0.4;
}
.deck-container > .slide .deck-before:not(.deck-child-current) .deck-before, .deck-container > .slide .deck-before:not(.deck-child-current) .deck-previous, .deck-container > .slide .deck-previous:not(.deck-child-current) .deck-before, .deck-container > .slide .deck-previous:not(.deck-child-current) .deck-previous {
opacity: 1;
}
.deck-container > .slide .deck-child-current {
opacity: 1;
}
.deck-container .deck-prev-link, .deck-container .deck-next-link {
background: #ccc;
font-family: serif;
}
.deck-container .deck-prev-link, .deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-prev-link:active, .deck-container .deck-prev-link:visited, .deck-container .deck-next-link, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus, .deck-container .deck-next-link:active, .deck-container .deck-next-link:visited {
color: #fff;
}
.deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus {
background: #c00;
text-decoration: none;
}
.deck-container .deck-status {
font-size: 0.6666em;
}
.deck-container.deck-menu .slide {
background: #eee;
}
.deck-container.deck-menu .deck-current, .no-touch .deck-container.deck-menu .slide:hover {
background: #ddf;
}

View file

@ -0,0 +1,903 @@
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>EO::MPI parallelization</title>
<meta name="description" content="A short presentation on EO::MPI parallelization">
<meta name="author" content="Benjamin BOUVIER">
<meta name="viewport" content="width=1024, user-scalable=no">
<!-- Core and extension CSS files -->
<link rel="stylesheet" href="css/deck.core.css">
<link rel="stylesheet" href="css/deck.goto.css">
<link rel="stylesheet" href="css/deck.menu.css">
<link rel="stylesheet" href="css/deck.navigation.css">
<link rel="stylesheet" href="css/deck.status.css">
<link rel="stylesheet" href="css/deck.hash.css">
<link rel="stylesheet" href="css/deck.scale.css">
<!-- Style theme. More available in /themes/style/ or create your own. -->
<!-- <link rel="stylesheet" href="../themes/style/web-2.0.css"> -->
<link rel="stylesheet" href="css/thales.css">
<link rel="stylesheet" href="css/eompi.css">
<!-- highlight js -->
<link rel="stylesheet" href="css/shjs.css">
<!-- Transition theme. More available in /themes/transition/ or create your own. -->
<link rel="stylesheet" href="css/horizontal-slide.css">
<script src="js/modernizr.custom.js"></script>
</head>
<body class="deck-container">
<!-- Begin slides -->
<section class="slide" id="title-slide">
<h1>EO's Parallelization with MPI</h1>
</section>
<section class="slide">
<h2>What is parallelization?</h2>
<ul>
<li><h3>Divide and Conquer paradigm</h3>
<p>A difficult problem can be splitted into simpler sub problems.</p>
<p>Therefore the sub problems should be solved faster.</p>
</li>
<li class="slide"><h3>Parallelize.</h3>
<p>Process serveral tasks together (<em>concurrent programming</em>).</p>
<p>By different ways :
<ul>
<li><em>Shared memory</em> : Multitask, OpenMP, etc.</li>
<li><em>Message Passing Interface</em> : MPI.</li>
<li>Other ways, undetailed here: <em>coroutines</em>, <em>multi-thread / LightWeightProcess</em>,
<em>Field Programmable Gate Array (FPGA)</em>, <em>General Purpose GPU (GPGPU)</em>, etc.</li>
</ul>
</p>
</li>
</ul>
</section>
<section class="slide">
<h2>Shared memory (e.g : OpenMP)</h2>
<ul>
<li class="slide"><strong>Multicore</strong> : more than one core per processor.
<ul>
<li>Processes several instruction streams together, each one manipulating different datas.</li>
<li>Different from <em>superscalar</em> processors, which can process more than one instruction during a
single processor cycle.</li>
<li>A multicore processor can however be superscalar.</li>
<li>For instance : <em>IBM's Cell microprocessor (PlayStation3)</em></li>
</ul>
</li>
<li class="slide"><strong>Symmetric multiprocessing</strong> : More than one processor which communicate through
a specific bus.
<ul>
<li><em>Bus contention</em> is the principal limitating factor.</li>
</ul>
</li>
<li class="slide">The main drawback is explicitly contained in the name.
<ul>
<li>Memory is <em>shared</em></li>
<li>Bus contention?</li>
<li>Low memory?</li>
<li>Use of virtual memory (swap) and page faults?</li>
<li>=> Can slow the speedup compared with the number of processors.</li>
</ul>
</li>
</ul>
</section>
<section class="slide">
<h2>Message Passing Interface (e.g : OpenMPI)</h2>
<p>Memory isn't shared here, manipulated objects are sent on a network: there is communication between the machines
(called <em>hosts</em>)</p>
<ul>
<li><strong>Cluster</strong>
<ul class="slide">
<li>Several machines network connected (for instance, in an Ethernet network).</li>
<li>Can have different specifications, but this can affect load balancing.</li>
<li>Most of the <em>supercomputers</em> are clusters.</li>
<li>For exemple : Beowulf Cluster, Sun Grid Engine...</li>
</ul>
</li>
<li><strong>Massive parallel processing</strong>
<ul class="slide">
<li>This is not machines but processors which are directly connected by network.</li>
<li>Like a cluster, but the networks are specific, so as to wire more processors.</li>
</ul>
</li>
<li><strong>Grid (a.k.a Distributed Computing)</strong>
<ul class="slide">
<li>Networks with potentially high latence and low bandwith, like Internet.</li>
<li>Example of programs : BOINC, Seti@home...</li>
</ul>
</li>
</ul>
</section>
<section class="slide">
<h1>Parallelization myths</h1>
</section>
<section class="slide">
<h2>A myth about speed: the car's enigma</h2>
<ul>
<li class="slide">If a car has to travel 100 Km, but has yet traveled 60 Km in 1 hour (i.e it has an average
speed of 60 Km per hour), what is its maximal average speed on the whole traject
?</li>
<p><img src="http://www.canailleblog.com/photos/blogs/chevaux-trop-rigolo-229540.jpg" /></p>
<li class="slide">Some hints:
<ul>
<li>The driver can use all the hilarious gas (N<sub>2</sub>O, nitrous oxyde, a.k.a <em>nitro</em>) he
needs.</li>
<li>Let's suppose even that the car can travel at speed of light, or teleport (despite general theory of
relativity).</li>
</ul>
</li>
<li class="slide">The solution: <strong>100 Km/h</strong></li>
<li class="slide">The explanation: let's suppose that the car teleports after the first 60 Km. It would have
traveled 60 Km in 1 hour and 40 Km in 0 seconds, which is 100 Km in 1 hour: 100 Km/h.</li>
</ul>
</section>
<section class="slide">
<h2>A myth about speed: "Il dit qu'il voit pas le rapport ?"</h2>
<p><img src="http://r.linter.fr/questionnaire/document/image/250/7241.jpg" /></p>
<ul class="slide">
<li>Let P be the parallelizable proportion of the program (~ the remaining distance to travel), which can be
processed by N machines.</li>
<li>Then 1 - P is the sequential (non parallelizable) proportion of the program (~ the already traveled distance), which
can be processed by 1 machine.</li>
<li>A sequential version would take 1 - P + P = 1 unit (of time) to terminate.</li>
<li>A parallel version would take (1-P) + P / N units to terminate.</li>
<li>The <em>speedup</em> (gain of speed) would then be:
<img src="http://upload.wikimedia.org/wikipedia/en/math/f/4/0/f40f1968282e110c7e65222d2b5d3115.png"
style="height:100px;"/>
which tends to 1-P as N tends to infinity.</li>
<li>The maximal theoritical speedup (~ maximal average speed) would then be 1 / (1-P)</li>
<li><h3>This result is known as Amdahl's law</h3></li>
</ul>
</section>
<section class="slide">
<h2>A myth about data : the cat's enigma</h2>
<ul>
<li class="slide">
<p>If 3 cats catch 3 mices in 3 minutes, how many cats are needed to catch 9 mices in 9
minutes ?
<img src="http://www.creabar.com/photo/Animaux/ggq91fch.jpg" />
</p>
</li>
<li class="slide">The solution: 3 too !</li>
<li class="slide">A better question to ask would be: how many mices can catch 9 cats in 3 minutes ?</li>
</ul>
</section>
<section class="slide">
<h2>A myth about data</h2>
<ul>
<li>The idea is no more to make a processing faster (for a constant amount of data) but to process more data (in
the same time).</li>
<li>In this case, the most hosts we add, the most data we can process at a time.</li>
<li>This doesn't contradict Amdahl's Law, which makes the assumption that the amount of data to process stays
the same.</li>
<li>There is also another way to calculate speedup here:
<img src="http://upload.wikimedia.org/wikipedia/en/math/1/9/f/19f6e664e94fbcaa0f5877d74b6bffcd.png"
style="height: 50px;" />
where P is the number of processes, alpha the non parallelizable part of the program.
</li>
<li><h3>This result is known as the Gustafson's Law</h3></li>
</ul>
</section>
<section class="slide">
<h2>A metric: speedup</h2>
<ul>
<li><strong>Speedup</strong> refers to how much a parallel algorithm is faster than a corresponding sequential algorithm</li>
<li>It's a quantitative mesure, relative to the sequential version :
<img src="http://upload.wikimedia.org/wikipedia/en/math/a/8/0/a8080d5bd23d7ba57a9cf4fedcefadad.png"
style="height:100px;"/>
where T<sub>1</sub> is the time taken by the sequential version and T<sub>p</sub> the time taken by the parallel version with p
processes.
</li>
<li>A speedup equal to one indicates that the version is as performant as the sequential version.</li>
<li>Practically, speedup may not be linear in number of processes (Amdahl's Law)</li>
</ul>
</section>
<section class="slide">
<h1>Parallelization in EO</h1>
</section>
<section class="slide">
<h2>Objectives</h2>
<ul>
<li>Remember, tasks have to be independant from one to another.</li>
<li>Process data faster: what takes time in EO?
<ul class="slide">
<li>Evaluation!</li>
</ul>
</li>
<li>Process more data during the same time: where?
<ul class="slide">
<li>Multi-start!</li>
</ul>
</li>
<li>Other objectives :
<ul>
<li>Readily serialize EO objects.</li>
<li>Be able to easily implement other parallel algorithms.</li>
</ul>
</li>
</ul>
</section>
<section class="slide">
<h2>Evaluation: Long story short</h2>
<pre class="sh_cpp"><code>
int main( int argc, char **argv )
{
eo::mpi::Node::init( argc, argv );
// PUT EO STUFF HERE
// Let's make the assumption that pop is a eoPop&lt;EOT&gt;
// and evalFunc is an evaluation functor
eo::mpi::DynamicAssignmentAlgorithm assign;
eoParallelPopLoopEval&lt;EOT&gt; popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
popEval( pop, pop );
}
</code></pre>
</section>
<section class="slide">
<h2>Serializing EO objects</h2>
<ul>
<li>Serializing is writing a message from a binary source into a message transmissible data.</li>
<li>Several formats can be used
<ul class="slide">
<li>Binary directly - but all the hosts have to be the same!</li>
<li>Text based formats: XML, YAML, JSON,...</li>
</ul>
</li>
<li>So why use text?
<ul class="slide">
<li>It's human readable, more or less easily parsable.</li>
<li>It's independant from the data type representations on the machines (e.g: an int on a 32 bits and on
a 64 bits machines are not the same).</li>
<li>Main drawbacks: it takes more space and it needs a processing for encoding and decoding.</li>
</ul>
</li>
</ul>
</section>
<section class="slide">
<h2>eoserial : principle</h2>
<img src="./img/serialisation.png" style="float:left;margin-right:25px;" />
<ul>
<li>JSON serialization
<ul class="slide">
<li>Lighter than XML.</li>
<li>Easily parsable, the grammar is trivial.</li>
<li>Allows to represent tables, objects and texts: it's sufficient!</li>
</ul>
</li>
<li>What happens in your life when you're serializable?
</li>
<li>Implement interface eoserial::Persistent and your object can be saved and loaded, in JSON format.</li>
<li>No need to serialize the whole object, you choose what you need to save and load.</li>
<li>Everything can be serialized!<ul class="slide">
<li>Atomic types are directly serialized into eoserial::String (thanks to std::stringstream)</li>
<li>Arrays are serializable (into eoserial::Array), if what they contain is too.</li>
<li>Object can be serializable (into eoserial::Object), if what they contain is too.</li>
</ul></li>
</ul>
</section>
<section class="slide">
<h2>eoserial : interface eoserial::Persistent</h2>
<pre class="sh_cpp">
<code>
# include &lt;serial/eoSerial.h&gt;
class MyObject : public eoserial::Persistent {
public:
// A persistent class needs a default empty ctor.
MyObject() {}
int id;
// Implementation of eoserial::Persistent::pack
// What to save when making a serialized object?
eoserial::Object* pack() const
{
eoserial::Object* obj = new eoserial::Object;
// eoserial::make creates a eoserial::String from a basic type
eoserial::String* idAsString = eoserial::make( id );
// the key "saved_id" will be associated to the JSON object idAsString
obj->add( "saved_id", idAsString );
// could have be done with
// (*obj)["saved_id"] = idAsString;
// as obj is a std::map pointer
return obj;
}
// Implementation of eoserial::Persistent::unpack
// What data to retrieve from a JSON object and where to put it?
void unpack(const eoserial::Object* json)
{
// retrieves the value from key "saved_id" in "*json" object and put it into member "id"
eoserial::unpack( *json, "saved_id" , id );
}
};
</code>
</pre>
</section>
<section class="slide">
<h2>eoserial : use it</h2>
<pre class="sh_cpp">
<code>
# include &lt;eoSerial.h&gt;
# include &lt;fstream&gt;
# include &lt;cassert&gt;
int main(void)
{
MyObject instance;
instance.id = 42;
// Writes
eoserial::Object* obj = instance.pack();
std::ofstream ofile("filename");
obj->print( ofile );
ofile.close();
delete obj;
// Reads
std::ifstream ifile("filename");
std::stringstream ss;
while( ifile )
{
std::string s;
ifile &gt;&gt; s;
ss &lt;&lt; s;
}
eoserial::Object* objCopy = eoserial::Parser::parse( ss.str() );
MyObject instanceCopy;
instanceCopy.unpack( objCopy );
assert( instanceCopy.id == instance.id );
return 0;
}
</code>
</pre>
</section>
<section class="slide">
<h2>eoserial : more complex uses</h2>
<pre class="sh_cpp"><code>
struct ComplexObject
{
bool someBooleanValue; // will be serialized into a string
MyObject obj; // Objects can contain other objects too
std::vector&lt;int&gt;; // and tables too!
};
int main(void)
{
ComplexObject co;
// let's imagine we've set values of co.
eoserial::Object* json = new eoserial::Object;
// serialize basic type
(*json)["some_boolean_value"] = eoserial::make( co.someBooleanValue );
// MyObject is Persistent, so eoserial knows how to serialize it
json->add( "my_object", &co.obj );
// Instead of having a "for" loop, let's automatically serialize the content of the array
json->add( "int_array",
eoserial::makeArray&lt; std::vector&lt;int&gt;, eoserial::MakeAlgorithm &gt;( co.array ) );
// Print everything on the standard output
json->print( std::cout );
delete json;
return 0;
}
</code></pre>
</section>
<section class="slide">
<h2>MPI</h2>
<ul>
<li>We know how to serialize our objects. Now, we need to transmit them over the network.</li>
<li><strong>Message Passing Interface</strong> (MPI) is a norm.</li>
<li>OpenMPI implements it, in C, in the SPMD (Single Program Multiple Data) fashion. It is an active community
and the library is very well documented.</li>
<li>Boost::mpi gives it a C++ flavour (and tests each status code returned by MPI calls, throwing up exceptions
instead).</li>
<li>MPI helps by:
<ul class="slide">
<li>Managing the administration of roles: each MPI process has a <em>rank</em> and knows the whole
<em>size</em> of the cluster.</li>
<li>Regrouping outputs of different processes into one single output.</li>
<li>Managing the routing of messages and connections between the processes.</li>
<li>Launch a given number of processes via SSH, or a cluster engine (like SGE).</li>
</ul>
</li>
<li>MPI doesn't deal with:
<ul class="slide">
<li>Debugging: if one of your program segfaults, buy a parallel debugger or... Good luck!</li>
<li>More generally, knowing what happens: even the standard output becomes a shared resource without any
protection!</li>
</ul>
</li>
</ul>
</section>
<section class="slide">
<h1>Design of parallel algorithms</h1>
</section>
<section class="slide">
<h2>Some vocabulary</h2>
<ul>
<li>In the most of cases, we want the results to be retrieved in one place. Besides, communication in MPI is
synchronous (it's a design choice making things are simpler).</li>
<li>One process will have particular responsabilities, like aggregating results: it's the <strong>master</strong>.</li>
<li>Other processes will be used to do the processing (it's the goal, after all?) : they're the
<strong>workers</strong>. Or <strong>slaves</strong>, but it may be <em>patronizing</em> and the master is rarely called
the <em>patron</em>.</li>
<li>As there is one master, the algorithm is said to be <strong>centralized</strong>. Some well-known parallel algorithms
use this paradigm: <em>Google's MapReduce</em>, <em>Apache's Hadoop</em>(free implementation of Google's one :-)),...</li>
<li>A <strong>job</strong> is the parallel algorithm seen in its globality (i.e., as a function).</li>
<li>A job is a set of <strong>tasks</strong>, which are the atomic, decomposed part which can be serialized and
processed by a worker, at a time.</li>
</ul>
</section>
<section class="slide">
<h2>Evaluation (1/2)</h2>
<p>
Let's see how we could implement our parallelized evaluation<br/>
It's feasible as evaluating an individual is independant from evaluating another one.<br/>
<pre><code>
// On master side
function parallel_evaluate( population p )
foreach individual i in p,
send i to a worker
if there is no available worker,
wait for any response (return)
and retry
endif
endforeach
inform all the available workers that they are done (yes, it's a centralized algorithm)
wait for all remaining responses
endfunction
when receiving a response:
replace the evaluated individual in the population
// On worker side
function parallel_evaluate( evaluation function f )
wait for a individual i
apply f on it
send i to the master
endfunction
</code></pre>
</p>
</section>
<section class="slide">
<h2>Evaluation (2/2)</h2>
<p>But a parallelization algorithm is interesting only if the process time is higher than the
communication time. If process time is too short relatively to the communication time, we can do the following:
<pre><code>
// On master side<span class="changed">
function parallel_evaluate( population p, number of elements to send each time packet_size )
index = 0
while index &lt; size
sentSize := how many individuals (&lt;= packet_size) can we send to a worker?
find a worker. If there is no one, wait for any response (return) and retry
send the sentSize to the worker
send the individuals to the worker
index += sentSize
endwhile</span>
inform all the available workers that they're done
wait for all remaining responses
endfunction
when receiving a response:
replace the evaluated individuals in the population
// On worker side
function parallel_evaluate( evaluation function f )
<span class="changed">size := wait for a sentSize as described above
individuals := wait for size individuals
apply f on each of them
send back the individuals</span>
endfunction
</code></pre>
</section>
<section class="slide">
<h2>Multi start</h2>
<p>The idea behing multi-start is to run many times the same algorithm (for instance, eoEasyEA), but with different
seeds: the workers launch the algorithm and send their solutions as they come to the master, which saves the
ultimate best solution.</p>
<pre>
// On master side
variable best_score (initialized at the worst value ever) // score can be fitness, for instance
function parallel_multistart( integer runs )
seeds = table of generated seeds, or fixed seeds, whose size is at least "runs"
for i := 0; i &lt; runs; ++i
find a worker. If there is no one, wait for any response (return) and retry
send to the worker a different seed
endfor
inform all the available workers that they're done
wait for all remaining responses
endfunction
when receiving a response:
received_score := receive score from the worker.
If the received_score &gt; best_score
send worker a message indicating that master is interested by the solution
receive the solution
updates the best_score
else
send worker a message indicating that master isn't interested by the solution
endif
// On worker side
function parallel_multistart( algorithm eoAlgo )
seed := wait for a seed
solution := eoAlgo( seed )
send solution score to master
master_is_interested := wait for the response
if master_is_interested
send solution to master
endif
endfunction
</pre>
</section>
<section class="slide">
<h2>Common parts vs specific parts</h2>
<ul>
<li>These two algorithms have common parts and specific parts.</li>
<li>Identifying them allows to design generic parallel algorithms.</li>
<li>In the following code sample, specific parts are in red. Everything else is hence generic.</li>
</ul>
<pre><code>
// On master side
function parallel_evaluate(<span class="specific">population p, number of elements to send each time packet_size </span>)
<span class="specific">index = 0</span>
while <span class="specific">index &lt; size</span>
find a worker. If there is no one, wait for any response (return) and retry
<span class="specific">sentSize := how many individuals (&lt;= packet_size) can we send to a worker?
send the sentSize to the worker
send the individuals to the worker
index += sentSize</span>
endwhile</span>
inform all the available workers that they're done
wait for all remaining responses
endfunction
when receiving a response:
<span class="specific">replace the evaluated individuals in the population</span>
// On worker side
function parallel_evaluate(<span class="specific"> evaluation function f </span>)
<span class="specific">size := wait for a sentSize as described above
individuals := wait for size individuals
apply f on each of them
send back the individuals</span>
endfunction
</code></pre>
</section>
<section class="slide">
<h2>Common parts</h2>
<ul>
<li>Master runs a loop.</li>
<li>Master has to manage workers (find them, wait for them, etc...)</li>
<li>Workers need to be informed if they have something to do or not (stop condition in master part)</li>
<li>Master needs to wait to get all the responses.</li>
</ul>
</section>
<section class="slide">
<h2>Specific parts</h2>
<ul>
<li>Loop condition in the master's part.</li>
<li>What has to be sent to a worker by master?</li>
<li>What has to be done by a worker when it receives an order?</li>
<li>What has to be done when the master receives a response?</li>
</ul>
</section>
<section class="slide">
<h2>Generic parallel algorithm</h2>
<p>The calls to specific parts are in red.</p>
<pre><code>
// Master side
function parallel_algorithm()
while ! <span class="specific">isFinished()</span>
worker := none
while worker is none
wait for a response and affect worker the origin of the response
<span class="specific">handleResponse( worker )</span>
worker = retrieve worker
endwhile
send worker a work order
<span class="specific">sendTask( worker )</span>
endwhile
foreach available worker
indicate worker it's done (send them a termination order)
endforeach
while all responses haven't be received
worker := none
wait for a response and affect worker the origin of the response
<span class="specific">handleResponse( worker )</span>
send worker a termination order
endwhile
endfunction
// Worker side
function parallel_algorithm()
order := receive order
while order is not termination order
<span class="specific">processTask( )</span>
order = receive order
endwhile
endfunction
</code></pre>
</section>
<section class="slide">
<h2>TLDR;</h2>
<img src="./img/generic_parallel.png" style="height:800px;"/>
</section>
<section class="slide">
<h2>Functors</h2>
<ul>
<li>Using functors allows them to wrap <em>and</em> be wrapped (decorator pattern).</li>
<li>IsFinished : implements <em>bool operator()()</em>, indicating that the job is over.</li>
<li>SendTask : implements <em>void operator()( int worker_rank )</em>, indicating what to send to the
worker.</li>
<li>ProcessTask : implements <em>void operator()()</em>, indicating what the worker has to do when it receives a
task.</li>
<li>HandleResponse : implements <em>void operator()( int worker_rank )</em>, indicating what to do when
receiving a worker response.</li>
<li>Implementing these 4 functors is sufficient for a parallel algorithm!</li>
<li>You can also wrap the existing one to add functionalities.</li>
</ul>
</section>
<section class="slide">
<h2>Stores</h2>
<ul>
<li>These 4 functors can use about the same data.</li>
<li>This data needs to be shared : all the functors are templated on a JobData structure.</li>
<li>A job needs data and functors to be launched.</li>
<li>Several jobs can use the same data and functors.</li>
<li>=> Data and functors are saved into a store, which can be reused between different jobs.</li>
</ul>
</section>
<section class="slide">
<h2>Scheduling tasks between workers</h2>
<ul>
<li>Until here, we don't know how to schedule tasks between workers.</li>
<li>Naive, simple solution: as soon as a worker has finished a task, give it a new task. Workers are put in a
queue, this is the <strong>dynamic assignment</strong> (scheduling).</li>
<li>If the worker's number of call is well-known, initially give to each worker a fixed amount of tasks. When a
worker has finished a task, give it another task only if it the amount of remaining tasks is positive ; else,
wait for another worker. Workers are managed with a fixed table, this is the <strong>static
assignment</strong>.</li>
</ul>
</section>
<section class="slide">
<h2>Let's go back to evaluation in EO</h2>
<ul>
<li>The idea behind applying a functor to each element of a table is very generic. Google, Python and Javascript
call it <strong>map</strong>, we call it <strong>ParallelApply</strong>, according to existing
<strong>apply</strong> function, in apply.h.</li>
<li>There is also a <em>ParallelApplyJob</em>, a <em>ParallelApplyStore</em> which contains a
<em>ParallelApplyData</em>, a <em>IsFinishedParallelApply</em>, etc...</li>
<li>This is what is used when calling parallel evaluation.</li>
</ul>
</section>
<section class="slide">
<h2>Customizing evaluation: reminder</h2>
<pre class="sh_cpp"><code>
int main( int argc, char **argv )
{
eo::mpi::Node::init( argc, argv );
// PUT EO STUFF HERE
// Let's make the assumption that pop is a eoPop&lt;EOT&gt;
// and evalFunc is an evaluation functor
eo::mpi::DynamicAssignmentAlgorithm assign;
eoParallelPopLoopEval&lt;EOT&gt; popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
// The store is hidden behind this call, but it can be given at eoParallelPopLoopEval constructor!
popEval( pop, pop );
}
</code></pre>
</section>
<section class="slide">
<h2>Customizing evaluation: the idea</h2>
<ul>
<li>We would like to retrieve best individuals, as soon as they're processed, and print their fitness in the
standard output, for instance.</li>
<li>We can wrap one of the 4 functors.</li>
<li>Master side or worker side?
<ul class="slide">
<li>Master side: we want to retrieve the <em>global</em> best individual, not the best individual in
population slices.</li>
<li>We have 3 choices: IsFinished, HandleResponse, SendTask.</li>
<li>So which one?
<ul class="slide">
<li>The functor HandleResponse should be reimplemented: in a sequential version, it would be done just
after the evaluation of an individual. The HandleResponse is the nearest functor called after having
received the result.</li>
</ul>
</li>
</ul>
</li>
<li>How to do it?
<ol class="slide">
<li>Retrieve which slice has been processed by the worker.</li>
<li>Call the embedded HandleResponse.</li>
<li>Compare the fitnesses of individuals in the slice to the global best individual.</li>
</ol>
</li>
</ul>
</section>
<section class="slide">
<h2>Customizing evaluation: implementation!</h2>
<pre class="sh_cpp"><code>
// Our objective is to minimize fitness, for instance
struct CatBestAnswers : public eo::mpi::HandleResponseParallelApply&lt;EOT&gt;
{
CatBestAnswers()
{
best.fitness( 1000000000. );
}
void operator()(int wrkRank)
{
// Retrieve informations about the slice processed by the worker
int index = _data->assignedTasks[wrkRank].index;
int size = _data->assignedTasks[wrkRank].size;
// call to the wrapped function HERE
(*_wrapped)( wrkRank );
// Compare fitnesses of evaluated individuals with the best saved
for(int i = index; i &lt; index+size; ++i)
{
if( best.fitness() &lt; _data->table()[ i ].fitness() )
{
eo::log &lt;&lt; eo::quiet &lt;&lt; "Better solution found:" &lt;&lt; _data->table()[i].fitness() &lt;&lt; std::endl;
best = _data->table()[ i ];
}
}
}
protected:
EOT best;
};
</code></pre>
</section>
<section class="slide">
<h2>Using customized handler</h2>
<pre class="sh_cpp"><code>
int main( int argc, char **argv )
{
eo::mpi::Node::init( argc, argv );
// PUT EO STUFF HERE
// Let's make the assumption that pop is a eoPop&lt;EOT&gt;
// and evalFunc is an evaluation functor
eo::mpi::DynamicAssignmentAlgorithm assign;
// What was used before
// eoParallelPopLoopEval&lt;EOT&gt; popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
// What's new
eo::mpi::ParallelApplyStore&lt; EOT &gt; store( evalFunc, eo::mpi::DEFAULT_MASTER );
CatBestAnswer catBestAnswers;
store.wrapHandleResponse( &catBestAnswers );
eoParallelPopLoopEval&lt; EOT &gt; popEval( assign, eo::mpi::DEFAULT_MASTER, &store );
// What doesn't change
popEval( pop, pop );
}
</code></pre>
</section>
<section class="slide">
<h1>Thank you for your attention</h1>
</section>
<section class="slide">
<h2>Remarks</h2>
<ul>
<li>This presentation is made of HTML5, CSS3, JavaScript, thanks to frameworks
<a href="http://imakewebthings.com/deck.js/">Deck.js</a> (slides) and <a href="http://shjs.sourceforge.net/">SHJS</a> (syntax
highlighting).
<li>If you have any complaint to make, please refer to <a href="mailto:johann@dreo.fr">Johann Dreo</a>.</li>
<li>If you have any question or compliment, please refer to <a href="mailto:benjamin.bouvier@gmail.com">me</a>
(Benjamin Bouvier).</li>
</ul>
</section>
<!-- deck.navigation snippet -->
<a href="#" class="deck-prev-link" title="Précédent">&#8592;</a>
<a href="#" class="deck-next-link" title="Suivant">&#8594;</a>
<!-- deck.status snippet -->
<p class="deck-status">
<span class="deck-status-current"></span>
/
<span class="deck-status-total"></span>
</p>
<!-- deck.goto snippet -->
<form action="." method="get" class="goto-form">
<label for="goto-slide">Go to slide:</label>
<input type="text" name="slidenum" id="goto-slide" list="goto-datalist">
<datalist id="goto-datalist"></datalist>
<input type="submit" value="Go">
</form>
<!-- deck.hash snippet -->
<a href="." title="Permalink to this slide" class="deck-permalink">#</a>
<!-- Grab CDN jQuery, with a protocol relative URL; fall back to local if offline -->
<!-- <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"></script> -->
<script>window.jQuery || document.write('<script src="js/jquery-1.7.min.js"><\/script>')</script>
<!-- Deck Core and extensions -->
<script src="js/deck.core.js"></script>
<script src="js/deck.hash.js"></script>
<script src="js/deck.menu.js"></script>
<script src="js/deck.goto.js"></script>
<script src="js/deck.status.js"></script>
<script src="js/deck.navigation.js"></script>
<script src="js/deck.scale.js"></script>
<!-- Initialize the deck -->
<script>
$(function() {
$.deck('.slide');
});
</script>
<!-- Initialize the highlighter -->
<script src="js/shjs.js"></script>
<script src="js/shjs-cpp.js"></script>
<script>
sh_highlightDocument();
</script>
</body>
</html>

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View file

@ -0,0 +1,498 @@
/*!
Deck JS - deck.core
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
The deck.core module provides all the basic functionality for creating and
moving through a deck. It does so by applying classes to indicate the state of
the deck and its slides, allowing CSS to take care of the visual representation
of each state. It also provides methods for navigating the deck and inspecting
its state, as well as basic key bindings for going to the next and previous
slides. More functionality is provided by wholly separate extension modules
that use the API provided by core.
*/
(function($, deck, document, undefined) {
var slides, // Array of all the uh, slides...
current, // Array index of the current slide
$container, // Keeping this cached
events = {
/*
This event fires whenever the current slide changes, whether by way of
next, prev, or go. The callback function is passed two parameters, from
and to, equal to the indices of the old slide and the new slide
respectively. If preventDefault is called on the event within this handler
the slide change does not occur.
$(document).bind('deck.change', function(event, from, to) {
alert('Moving from slide ' + from + ' to ' + to);
});
*/
change: 'deck.change',
/*
This event fires at the beginning of deck initialization, after the options
are set but before the slides array is created. This event makes a good hook
for preprocessing extensions looking to modify the deck.
*/
beforeInitialize: 'deck.beforeInit',
/*
This event fires at the end of deck initialization. Extensions should
implement any code that relies on user extensible options (key bindings,
element selectors, classes) within a handler for this event. Native
events associated with Deck JS should be scoped under a .deck event
namespace, as with the example below:
var $d = $(document);
$.deck.defaults.keys.myExtensionKeycode = 70; // 'h'
$d.bind('deck.init', function() {
$d.bind('keydown.deck', function(event) {
if (event.which === $.deck.getOptions().keys.myExtensionKeycode) {
// Rock out
}
});
});
*/
initialize: 'deck.init'
},
options = {},
$d = $(document),
/*
Internal function. Updates slide and container classes based on which
slide is the current slide.
*/
updateStates = function() {
var oc = options.classes,
osc = options.selectors.container,
old = $container.data('onSlide'),
$all = $();
// Container state
$container.removeClass(oc.onPrefix + old)
.addClass(oc.onPrefix + current)
.data('onSlide', current);
// Remove and re-add child-current classes for nesting
$('.' + oc.current).parentsUntil(osc).removeClass(oc.childCurrent);
slides[current].parentsUntil(osc).addClass(oc.childCurrent);
// Remove previous states
$.each(slides, function(i, el) {
$all = $all.add(el);
});
$all.removeClass([
oc.before,
oc.previous,
oc.current,
oc.next,
oc.after
].join(" "));
// Add new states back in
slides[current].addClass(oc.current);
if (current > 0) {
slides[current-1].addClass(oc.previous);
}
if (current + 1 < slides.length) {
slides[current+1].addClass(oc.next);
}
if (current > 1) {
$.each(slides.slice(0, current - 1), function(i, el) {
el.addClass(oc.before);
});
}
if (current + 2 < slides.length) {
$.each(slides.slice(current+2), function(i, el) {
el.addClass(oc.after);
});
}
},
/* Methods exposed in the jQuery.deck namespace */
methods = {
/*
jQuery.deck(selector, options)
selector: string | jQuery | array
options: object, optional
Initializes the deck, using each element matched by selector as a slide.
May also be passed an array of string selectors or jQuery objects, in
which case each selector in the array is considered a slide. The second
parameter is an optional options object which will extend the default
values.
$.deck('.slide');
or
$.deck([
'#first-slide',
'#second-slide',
'#etc'
]);
*/
init: function(elements, opts) {
var startTouch,
tolerance,
esp = function(e) {
e.stopPropagation();
};
options = $.extend(true, {}, $[deck].defaults, opts);
slides = [];
current = 0;
$container = $(options.selectors.container);
tolerance = options.touch.swipeTolerance;
// Pre init event for preprocessing hooks
$d.trigger(events.beforeInitialize);
// Hide the deck while states are being applied to kill transitions
$container.addClass(options.classes.loading);
// Fill slides array depending on parameter type
if ($.isArray(elements)) {
$.each(elements, function(i, e) {
slides.push($(e));
});
}
else {
$(elements).each(function(i, e) {
slides.push($(e));
});
}
/* Remove any previous bindings, and rebind key events */
$d.unbind('keydown.deck').bind('keydown.deck', function(e) {
if (e.which === options.keys.next || $.inArray(e.which, options.keys.next) > -1) {
methods.next();
e.preventDefault();
}
else if (e.which === options.keys.previous || $.inArray(e.which, options.keys.previous) > -1) {
methods.prev();
e.preventDefault();
}
});
/* Bind touch events for swiping between slides on touch devices */
$container.unbind('touchstart.deck').bind('touchstart.deck', function(e) {
if (!startTouch) {
startTouch = $.extend({}, e.originalEvent.targetTouches[0]);
}
})
.unbind('touchmove.deck').bind('touchmove.deck', function(e) {
$.each(e.originalEvent.changedTouches, function(i, t) {
if (startTouch && t.identifier === startTouch.identifier) {
if (t.screenX - startTouch.screenX > tolerance || t.screenY - startTouch.screenY > tolerance) {
$[deck]('prev');
startTouch = undefined;
}
else if (t.screenX - startTouch.screenX < -1 * tolerance || t.screenY - startTouch.screenY < -1 * tolerance) {
$[deck]('next');
startTouch = undefined;
}
return false;
}
});
e.preventDefault();
})
.unbind('touchend.deck').bind('touchend.deck', function(t) {
$.each(t.originalEvent.changedTouches, function(i, t) {
if (startTouch && t.identifier === startTouch.identifier) {
startTouch = undefined;
}
});
})
.scrollLeft(0).scrollTop(0)
/* Stop propagation of key events within editable elements of slides */
.undelegate('input, textarea, select, button, meter, progress, [contentEditable]', 'keydown', esp)
.delegate('input, textarea, select, button, meter, progress, [contentEditable]', 'keydown', esp);
/*
Kick iframe videos, which dont like to redraw w/ transforms.
Remove this if Webkit ever fixes it.
*/
$.each(slides, function(i, $el) {
$el.unbind('webkitTransitionEnd.deck').bind('webkitTransitionEnd.deck',
function(event) {
if ($el.hasClass($[deck]('getOptions').classes.current)) {
var embeds = $(this).find('iframe').css('opacity', 0);
window.setTimeout(function() {
embeds.css('opacity', 1);
}, 100);
}
});
});
if (slides.length) {
updateStates();
}
// Show deck again now that slides are in place
$container.removeClass(options.classes.loading);
$d.trigger(events.initialize);
},
/*
jQuery.deck('go', index)
index: integer | string
Moves to the slide at the specified index if index is a number. Index is
0-based, so $.deck('go', 0); will move to the first slide. If index is a
string this will move to the slide with the specified id. If index is out
of bounds or doesn't match a slide id the call is ignored.
*/
go: function(index) {
var e = $.Event(events.change),
ndx;
/* Number index, easy. */
if (typeof index === 'number' && index >= 0 && index < slides.length) {
ndx = index;
}
/* Id string index, search for it and set integer index */
else if (typeof index === 'string') {
$.each(slides, function(i, $slide) {
if ($slide.attr('id') === index) {
ndx = i;
return false;
}
});
};
/* Out of bounds, id doesn't exist, illegal input, eject */
if (typeof ndx === 'undefined') return;
$d.trigger(e, [current, ndx]);
if (e.isDefaultPrevented()) {
/* Trigger the event again and undo the damage done by extensions. */
$d.trigger(events.change, [ndx, current]);
}
else {
current = ndx;
updateStates();
}
},
/*
jQuery.deck('next')
Moves to the next slide. If the last slide is already active, the call
is ignored.
*/
next: function() {
methods.go(current+1);
},
/*
jQuery.deck('prev')
Moves to the previous slide. If the first slide is already active, the
call is ignored.
*/
prev: function() {
methods.go(current-1);
},
/*
jQuery.deck('getSlide', index)
index: integer, optional
Returns a jQuery object containing the slide at index. If index is not
specified, the current slide is returned.
*/
getSlide: function(index) {
var i = typeof index !== 'undefined' ? index : current;
if (typeof i != 'number' || i < 0 || i >= slides.length) return null;
return slides[i];
},
/*
jQuery.deck('getSlides')
Returns all slides as an array of jQuery objects.
*/
getSlides: function() {
return slides;
},
/*
jQuery.deck('getContainer')
Returns a jQuery object containing the deck container as defined by the
container option.
*/
getContainer: function() {
return $container;
},
/*
jQuery.deck('getOptions')
Returns the options object for the deck, including any overrides that
were defined at initialization.
*/
getOptions: function() {
return options;
},
/*
jQuery.deck('extend', name, method)
name: string
method: function
Adds method to the deck namespace with the key of name. This doesnt
give access to any private member data public methods must still be
used within method but lets extension authors piggyback on the deck
namespace rather than pollute jQuery.
$.deck('extend', 'alert', function(msg) {
alert(msg);
});
// Alerts 'boom'
$.deck('alert', 'boom');
*/
extend: function(name, method) {
methods[name] = method;
}
};
/* jQuery extension */
$[deck] = function(method, arg) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else {
return methods.init(method, arg);
}
};
/*
The default settings object for a deck. All deck extensions should extend
this object to add defaults for any of their options.
options.classes.after
This class is added to all slides that appear after the 'next' slide.
options.classes.before
This class is added to all slides that appear before the 'previous'
slide.
options.classes.childCurrent
This class is added to all elements in the DOM tree between the
'current' slide and the deck container. For standard slides, this is
mostly seen and used for nested slides.
options.classes.current
This class is added to the current slide.
options.classes.loading
This class is applied to the deck container during loading phases and is
primarily used as a way to short circuit transitions between states
where such transitions are distracting or unwanted. For example, this
class is applied during deck initialization and then removed to prevent
all the slides from appearing stacked and transitioning into place
on load.
options.classes.next
This class is added to the slide immediately following the 'current'
slide.
options.classes.onPrefix
This prefix, concatenated with the current slide index, is added to the
deck container as you change slides.
options.classes.previous
This class is added to the slide immediately preceding the 'current'
slide.
options.selectors.container
Elements matched by this CSS selector will be considered the deck
container. The deck container is used to scope certain states of the
deck, as with the onPrefix option, or with extensions such as deck.goto
and deck.menu.
options.keys.next
The numeric keycode used to go to the next slide.
options.keys.previous
The numeric keycode used to go to the previous slide.
options.touch.swipeTolerance
The number of pixels the users finger must travel to produce a swipe
gesture.
*/
$[deck].defaults = {
classes: {
after: 'deck-after',
before: 'deck-before',
childCurrent: 'deck-child-current',
current: 'deck-current',
loading: 'deck-loading',
next: 'deck-next',
onPrefix: 'on-slide-',
previous: 'deck-previous'
},
selectors: {
container: '.deck-container'
},
keys: {
// enter, space, page down, right arrow, down arrow,
next: [13, 32, 34, 39, 40],
// backspace, page up, left arrow, up arrow
previous: [8, 33, 37, 38]
},
touch: {
swipeTolerance: 60
}
};
$d.ready(function() {
$('html').addClass('ready');
});
/*
FF + Transforms + Flash video don't get along...
Firefox will reload and start playing certain videos after a
transform. Blanking the src when a previously shown slide goes out
of view prevents this.
*/
$d.bind('deck.change', function(e, from, to) {
var oldFrames = $[deck]('getSlide', from).find('iframe'),
newFrames = $[deck]('getSlide', to).find('iframe');
oldFrames.each(function() {
var $this = $(this),
curSrc = $this.attr('src');
if(curSrc) {
$this.data('deck-src', curSrc).attr('src', '');
}
});
newFrames.each(function() {
var $this = $(this),
originalSrc = $this.data('deck-src');
if (originalSrc) {
$this.attr('src', originalSrc);
}
});
});
})(jQuery, 'deck', document);

View file

@ -0,0 +1,170 @@
/*!
Deck JS - deck.goto
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds the necessary methods and key bindings to show and hide a form
for jumping to any slide number/id in the deck (and processes that form
accordingly). The form-showing state is indicated by the presence of a class on
the deck container.
*/
(function($, deck, undefined) {
var $d = $(document);
/*
Extends defaults/options.
options.classes.goto
This class is added to the deck container when showing the Go To Slide
form.
options.selectors.gotoDatalist
The element that matches this selector is the datalist element that will
be populated with options for each of the slide ids. In browsers that
support the datalist element, this provides a drop list of slide ids to
aid the user in selecting a slide.
options.selectors.gotoForm
The element that matches this selector is the form that is submitted
when a user hits enter after typing a slide number/id in the gotoInput
element.
options.selectors.gotoInput
The element that matches this selector is the text input field for
entering a slide number/id in the Go To Slide form.
options.keys.goto
The numeric keycode used to show the Go To Slide form.
options.countNested
If false, only top level slides will be counted when entering a
slide number.
*/
$.extend(true, $[deck].defaults, {
classes: {
goto: 'deck-goto'
},
selectors: {
gotoDatalist: '#goto-datalist',
gotoForm: '.goto-form',
gotoInput: '#goto-slide'
},
keys: {
goto: 71 // g
},
countNested: true
});
/*
jQuery.deck('showGoTo')
Shows the Go To Slide form by adding the class specified by the goto class
option to the deck container.
*/
$[deck]('extend', 'showGoTo', function() {
$[deck]('getContainer').addClass($[deck]('getOptions').classes.goto);
$($[deck]('getOptions').selectors.gotoInput).focus();
});
/*
jQuery.deck('hideGoTo')
Hides the Go To Slide form by removing the class specified by the goto class
option from the deck container.
*/
$[deck]('extend', 'hideGoTo', function() {
$($[deck]('getOptions').selectors.gotoInput).blur();
$[deck]('getContainer').removeClass($[deck]('getOptions').classes.goto);
});
/*
jQuery.deck('toggleGoTo')
Toggles between showing and hiding the Go To Slide form.
*/
$[deck]('extend', 'toggleGoTo', function() {
$[deck]($[deck]('getContainer').hasClass($[deck]('getOptions').classes.goto) ? 'hideGoTo' : 'showGoTo');
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions'),
$datalist = $(opts.selectors.gotoDatalist),
slideTest = $.map([
opts.classes.before,
opts.classes.previous,
opts.classes.current,
opts.classes.next,
opts.classes.after
], function(el, i) {
return '.' + el;
}).join(', '),
rootCounter = 1;
// Bind key events
$d.unbind('keydown.deckgoto').bind('keydown.deckgoto', function(e) {
var key = $[deck]('getOptions').keys.goto;
if (e.which === key || $.inArray(e.which, key) > -1) {
e.preventDefault();
$[deck]('toggleGoTo');
}
});
/* Populate datalist and work out countNested*/
$.each($[deck]('getSlides'), function(i, $slide) {
var id = $slide.attr('id'),
$parentSlides = $slide.parentsUntil(opts.selectors.container, slideTest);
if (id) {
$datalist.append('<option value="' + id + '">');
}
if ($parentSlides.length) {
$slide.removeData('rootIndex');
}
else if (!opts.countNested) {
$slide.data('rootIndex', rootCounter);
++rootCounter;
}
});
// Process form submittal, go to the slide entered
$(opts.selectors.gotoForm)
.unbind('submit.deckgoto')
.bind('submit.deckgoto', function(e) {
var $field = $($[deck]('getOptions').selectors.gotoInput),
ndx = parseInt($field.val(), 10);
if (!$[deck]('getOptions').countNested) {
if (ndx >= rootCounter) return false;
$.each($[deck]('getSlides'), function(i, $slide) {
if ($slide.data('rootIndex') === ndx) {
ndx = i + 1;
return false;
}
});
}
$[deck]('go', isNaN(ndx) ? $field.val() : ndx - 1);
$[deck]('hideGoTo');
$field.val('');
e.preventDefault();
});
// Dont let keys in the input trigger deck actions
$(opts.selectors.gotoInput)
.unbind('keydown.deckgoto')
.bind('keydown.deckgoto', function(e) {
e.stopPropagation();
});
});
})(jQuery, 'deck');

View file

@ -0,0 +1,141 @@
/*!
Deck JS - deck.hash
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds deep linking to individual slides, enables internal links
to slides within decks, and updates the address bar with the hash as the user
moves through the deck. A permalink anchor is also updated. Standard themes
hide this link in browsers that support the History API, and show it for
those that do not. Slides that do not have an id are assigned one according to
the hashPrefix option. In addition to the on-slide container state class
kept by core, this module adds an on-slide state class that uses the id of each
slide.
*/
(function ($, deck, window, undefined) {
var $d = $(document),
$window = $(window),
/* Collection of internal fragment links in the deck */
$internals,
/*
Internal only function. Given a string, extracts the id from the hash,
matches it to the appropriate slide, and navigates there.
*/
goByHash = function(str) {
var id = str.substr(str.indexOf("#") + 1),
slides = $[deck]('getSlides');
$.each(slides, function(i, $el) {
if ($el.attr('id') === id) {
$[deck]('go', i);
return false;
}
});
// If we don't set these to 0 the container scrolls due to hashchange
$[deck]('getContainer').scrollLeft(0).scrollTop(0);
};
/*
Extends defaults/options.
options.selectors.hashLink
The element matching this selector has its href attribute updated to
the hash of the current slide as the user navigates through the deck.
options.hashPrefix
Every slide that does not have an id is assigned one at initialization.
Assigned ids take the form of hashPrefix + slideIndex, e.g., slide-0,
slide-12, etc.
options.preventFragmentScroll
When deep linking to a hash of a nested slide, this scrolls the deck
container to the top, undoing the natural browser behavior of scrolling
to the document fragment on load.
*/
$.extend(true, $[deck].defaults, {
selectors: {
hashLink: '.deck-permalink'
},
hashPrefix: 'slide-',
preventFragmentScroll: true
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions');
$internals = $(),
slides = $[deck]('getSlides');
$.each(slides, function(i, $el) {
var hash;
/* Hand out ids to the unfortunate slides born without them */
if (!$el.attr('id') || $el.data('deckAssignedId') === $el.attr('id')) {
$el.attr('id', opts.hashPrefix + i);
$el.data('deckAssignedId', opts.hashPrefix + i);
}
hash ='#' + $el.attr('id');
/* Deep link to slides on init */
if (hash === window.location.hash) {
$[deck]('go', i);
}
/* Add internal links to this slide */
$internals = $internals.add('a[href="' + hash + '"]');
});
if (!Modernizr.hashchange) {
/* Set up internal links using click for the poor browsers
without a hashchange event. */
$internals.unbind('click.deckhash').bind('click.deckhash', function(e) {
goByHash($(this).attr('href'));
});
}
/* Set up first id container state class */
if (slides.length) {
$[deck]('getContainer').addClass(opts.classes.onPrefix + $[deck]('getSlide').attr('id'));
};
})
/* Update permalink, address bar, and state class on a slide change */
.bind('deck.change', function(e, from, to) {
var hash = '#' + $[deck]('getSlide', to).attr('id'),
opts = $[deck]('getOptions'),
osp = opts.classes.onPrefix,
$c = $[deck]('getContainer');
$c.removeClass(osp + $[deck]('getSlide', from).attr('id'));
$c.addClass(osp + $[deck]('getSlide', to).attr('id'));
$(opts.selectors.hashLink).attr('href', hash);
if (Modernizr.history) {
window.history.replaceState({}, "", hash);
}
});
/* Deals with internal links in modern browsers */
$window.bind('hashchange.deckhash', function(e) {
if (e.originalEvent && e.originalEvent.newURL) {
goByHash(e.originalEvent.newURL);
}
else {
goByHash(window.location.hash);
}
})
/* Prevent scrolling on deep links */
.bind('load', function() {
if ($[deck]('getOptions').preventFragmentScroll) {
$[deck]('getContainer').scrollLeft(0).scrollTop(0);
}
});
})(jQuery, 'deck', this);

View file

@ -0,0 +1,187 @@
/*!
Deck JS - deck.menu
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds the methods and key binding to show and hide a menu of all
slides in the deck. The deck menu state is indicated by the presence of a class
on the deck container.
*/
(function($, deck, undefined) {
var $d = $(document),
rootSlides; // Array of top level slides
/*
Extends defaults/options.
options.classes.menu
This class is added to the deck container when showing the slide menu.
options.keys.menu
The numeric keycode used to toggle between showing and hiding the slide
menu.
options.touch.doubletapWindow
Two consecutive touch events within this number of milliseconds will
be considered a double tap, and will toggle the menu on touch devices.
*/
$.extend(true, $[deck].defaults, {
classes: {
menu: 'deck-menu'
},
keys: {
menu: 77 // m
},
touch: {
doubletapWindow: 400
}
});
/*
jQuery.deck('showMenu')
Shows the slide menu by adding the class specified by the menu class option
to the deck container.
*/
$[deck]('extend', 'showMenu', function() {
var $c = $[deck]('getContainer'),
opts = $[deck]('getOptions');
if ($c.hasClass(opts.classes.menu)) return;
// Hide through loading class to short-circuit transitions (perf)
$c.addClass([opts.classes.loading, opts.classes.menu].join(' '));
/* Forced to do this in JS until CSS learns second-grade math. Save old
style value for restoration when menu is hidden. */
if (Modernizr.csstransforms) {
$.each(rootSlides, function(i, $slide) {
$slide.data('oldStyle', $slide.attr('style'));
$slide.css({
'position': 'absolute',
'left': ((i % 4) * 25) + '%',
'top': (Math.floor(i / 4) * 25) + '%'
});
});
}
// Need to ensure the loading class renders first, then remove
window.setTimeout(function() {
$c.removeClass(opts.classes.loading)
.scrollTop($[deck]('getSlide').offset().top);
}, 0);
});
/*
jQuery.deck('hideMenu')
Hides the slide menu by removing the class specified by the menu class
option from the deck container.
*/
$[deck]('extend', 'hideMenu', function() {
var $c = $[deck]('getContainer'),
opts = $[deck]('getOptions');
if (!$c.hasClass(opts.classes.menu)) return;
$c.removeClass(opts.classes.menu);
$c.addClass(opts.classes.loading);
/* Restore old style value */
if (Modernizr.csstransforms) {
$.each(rootSlides, function(i, $slide) {
var oldStyle = $slide.data('oldStyle');
$slide.attr('style', oldStyle ? oldStyle : '');
});
}
window.setTimeout(function() {
$c.removeClass(opts.classes.loading).scrollTop(0);
}, 0);
});
/*
jQuery.deck('toggleMenu')
Toggles between showing and hiding the slide menu.
*/
$[deck]('extend', 'toggleMenu', function() {
$[deck]('getContainer').hasClass($[deck]('getOptions').classes.menu) ?
$[deck]('hideMenu') : $[deck]('showMenu');
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions'),
touchEndTime = 0,
currentSlide,
slideTest = $.map([
opts.classes.before,
opts.classes.previous,
opts.classes.current,
opts.classes.next,
opts.classes.after
], function(el, i) {
return '.' + el;
}).join(', ');
// Build top level slides array
rootSlides = [];
$.each($[deck]('getSlides'), function(i, $el) {
if (!$el.parentsUntil(opts.selectors.container, slideTest).length) {
rootSlides.push($el);
}
});
// Bind key events
$d.unbind('keydown.deckmenu').bind('keydown.deckmenu', function(e) {
if (e.which === opts.keys.menu || $.inArray(e.which, opts.keys.menu) > -1) {
$[deck]('toggleMenu');
e.preventDefault();
}
});
// Double tap to toggle slide menu for touch devices
$[deck]('getContainer').unbind('touchstart.deckmenu').bind('touchstart.deckmenu', function(e) {
currentSlide = $[deck]('getSlide');
})
.unbind('touchend.deckmenu').bind('touchend.deckmenu', function(e) {
var now = Date.now();
// Ignore this touch event if it caused a nav change (swipe)
if (currentSlide !== $[deck]('getSlide')) return;
if (now - touchEndTime < opts.touch.doubletapWindow) {
$[deck]('toggleMenu');
e.preventDefault();
}
touchEndTime = now;
});
// Selecting slides from the menu
$.each($[deck]('getSlides'), function(i, $s) {
$s.unbind('click.deckmenu').bind('click.deckmenu', function(e) {
if (!$[deck]('getContainer').hasClass(opts.classes.menu)) return;
$[deck]('go', i);
$[deck]('hideMenu');
e.stopPropagation();
e.preventDefault();
});
});
})
.bind('deck.change', function(e, from, to) {
var container = $[deck]('getContainer');
if (container.hasClass($[deck]('getOptions').classes.menu)) {
container.scrollTop($[deck]('getSlide', to).offset().top);
}
});
})(jQuery, 'deck');

View file

@ -0,0 +1,91 @@
/*!
Deck JS - deck.navigation
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds clickable previous and next links to the deck.
*/
(function($, deck, undefined) {
var $d = $(document),
/* Updates link hrefs, and disabled states if last/first slide */
updateButtons = function(e, from, to) {
var opts = $[deck]('getOptions'),
last = $[deck]('getSlides').length - 1,
prevSlide = $[deck]('getSlide', to - 1),
nextSlide = $[deck]('getSlide', to + 1),
prevId = prevSlide ? prevSlide.attr('id') : undefined;
nextId = nextSlide ? nextSlide.attr('id') : undefined;
$(opts.selectors.previousLink)
.toggleClass(opts.classes.navDisabled, !to)
.attr('href', '#' + (prevId ? prevId : ''));
$(opts.selectors.nextLink)
.toggleClass(opts.classes.navDisabled, to === last)
.attr('href', '#' + (nextId ? nextId : ''));
};
/*
Extends defaults/options.
options.classes.navDisabled
This class is added to a navigation link when that action is disabled.
It is added to the previous link when on the first slide, and to the
next link when on the last slide.
options.selectors.nextLink
The elements that match this selector will move the deck to the next
slide when clicked.
options.selectors.previousLink
The elements that match this selector will move to deck to the previous
slide when clicked.
*/
$.extend(true, $[deck].defaults, {
classes: {
navDisabled: 'deck-nav-disabled'
},
selectors: {
nextLink: '.deck-next-link',
previousLink: '.deck-prev-link'
}
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions'),
slides = $[deck]('getSlides'),
$current = $[deck]('getSlide'),
ndx;
// Setup prev/next link events
$(opts.selectors.previousLink)
.unbind('click.decknavigation')
.bind('click.decknavigation', function(e) {
$[deck]('prev');
e.preventDefault();
});
$(opts.selectors.nextLink)
.unbind('click.decknavigation')
.bind('click.decknavigation', function(e) {
$[deck]('next');
e.preventDefault();
});
// Find where we started in the deck and set initial states
$.each(slides, function(i, $slide) {
if ($slide === $current) {
ndx = i;
return false;
}
});
updateButtons(null, ndx, ndx);
})
.bind('deck.change', updateButtons);
})(jQuery, 'deck');

View file

@ -0,0 +1,170 @@
/*!
Deck JS - deck.scale
Copyright (c) 2011-2012 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds automatic scaling to the deck. Slides are scaled down
using CSS transforms to fit within the deck container. If the container is
big enough to hold the slides without scaling, no scaling occurs. The user
can disable and enable scaling with a keyboard shortcut.
Note: CSS transforms may make Flash videos render incorrectly. Presenters
that need to use video may want to disable scaling to play them. HTML5 video
works fine.
*/
(function($, deck, window, undefined) {
var $d = $(document),
$w = $(window),
baseHeight, // Value to scale against
timer, // Timeout id for debouncing
rootSlides,
/*
Internal function to do all the dirty work of scaling the slides.
*/
scaleDeck = function() {
var opts = $[deck]('getOptions'),
obh = opts.baseHeight,
$container = $[deck]('getContainer'),
baseHeight = obh ? obh : $container.height();
// Scale each slide down if necessary (but don't scale up)
$.each(rootSlides, function(i, $slide) {
var slideHeight = $slide.innerHeight(),
$scaler = $slide.find('.' + opts.classes.scaleSlideWrapper),
scale = $container.hasClass(opts.classes.scale) ?
baseHeight / slideHeight :
1;
$.each('Webkit Moz O ms Khtml'.split(' '), function(i, prefix) {
if (scale === 1) {
$scaler.css(prefix + 'Transform', '');
}
else {
$scaler.css(prefix + 'Transform', 'scale(' + scale + ')');
}
});
});
}
/*
Extends defaults/options.
options.classes.scale
This class is added to the deck container when scaling is enabled.
It is enabled by default when the module is included.
options.classes.scaleSlideWrapper
Scaling is done using a wrapper around the contents of each slide. This
class is applied to that wrapper.
options.keys.scale
The numeric keycode used to toggle enabling and disabling scaling.
options.baseHeight
When baseHeight is falsy, as it is by default, the deck is scaled in
proportion to the height of the deck container. You may instead specify
a height as a number of px, and slides will be scaled against this
height regardless of the container size.
options.scaleDebounce
Scaling on the browser resize event is debounced. This number is the
threshold in milliseconds. You can learn more about debouncing here:
http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
*/
$.extend(true, $[deck].defaults, {
classes: {
scale: 'deck-scale',
scaleSlideWrapper: 'deck-slide-scaler'
},
keys: {
scale: 83 // s
},
baseHeight: null,
scaleDebounce: 200
});
/*
jQuery.deck('disableScale')
Disables scaling and removes the scale class from the deck container.
*/
$[deck]('extend', 'disableScale', function() {
$[deck]('getContainer').removeClass($[deck]('getOptions').classes.scale);
scaleDeck();
});
/*
jQuery.deck('enableScale')
Enables scaling and adds the scale class to the deck container.
*/
$[deck]('extend', 'enableScale', function() {
$[deck]('getContainer').addClass($[deck]('getOptions').classes.scale);
scaleDeck();
});
/*
jQuery.deck('toggleScale')
Toggles between enabling and disabling scaling.
*/
$[deck]('extend', 'toggleScale', function() {
var $c = $[deck]('getContainer');
$[deck]($c.hasClass($[deck]('getOptions').classes.scale) ?
'disableScale' : 'enableScale');
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions'),
slideTest = $.map([
opts.classes.before,
opts.classes.previous,
opts.classes.current,
opts.classes.next,
opts.classes.after
], function(el, i) {
return '.' + el;
}).join(', ');
// Build top level slides array
rootSlides = [];
$.each($[deck]('getSlides'), function(i, $el) {
if (!$el.parentsUntil(opts.selectors.container, slideTest).length) {
rootSlides.push($el);
}
});
// Use a wrapper on each slide to handle content scaling
$.each(rootSlides, function(i, $slide) {
$slide.children().wrapAll('<div class="' + opts.classes.scaleSlideWrapper + '"/>');
});
// Debounce the resize scaling
$w.unbind('resize.deckscale').bind('resize.deckscale', function() {
window.clearTimeout(timer);
timer = window.setTimeout(scaleDeck, opts.scaleDebounce);
})
// Scale once on load, in case images or something change layout
.unbind('load.deckscale').bind('load.deckscale', scaleDeck);
// Bind key events
$d.unbind('keydown.deckscale').bind('keydown.deckscale', function(e) {
if (e.which === opts.keys.scale || $.inArray(e.which, opts.keys.scale) > -1) {
$[deck]('toggleScale');
e.preventDefault();
}
});
// Enable scale on init
$[deck]('enableScale');
});
})(jQuery, 'deck', this);

View file

@ -0,0 +1,95 @@
/*!
Deck JS - deck.status
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/
/*
This module adds a (current)/(total) style status indicator to the deck.
*/
(function($, deck, undefined) {
var $d = $(document),
updateCurrent = function(e, from, to) {
var opts = $[deck]('getOptions');
$(opts.selectors.statusCurrent).text(opts.countNested ?
to + 1 :
$[deck]('getSlide', to).data('rootSlide')
);
};
/*
Extends defaults/options.
options.selectors.statusCurrent
The element matching this selector displays the current slide number.
options.selectors.statusTotal
The element matching this selector displays the total number of slides.
options.countNested
If false, only top level slides will be counted in the current and
total numbers.
*/
$.extend(true, $[deck].defaults, {
selectors: {
statusCurrent: '.deck-status-current',
statusTotal: '.deck-status-total'
},
countNested: true
});
$d.bind('deck.init', function() {
var opts = $[deck]('getOptions'),
slides = $[deck]('getSlides'),
$current = $[deck]('getSlide'),
ndx;
// Set total slides once
if (opts.countNested) {
$(opts.selectors.statusTotal).text(slides.length);
}
else {
/* Determine root slides by checking each slide's ancestor tree for
any of the slide classes. */
var rootIndex = 1,
slideTest = $.map([
opts.classes.before,
opts.classes.previous,
opts.classes.current,
opts.classes.next,
opts.classes.after
], function(el, i) {
return '.' + el;
}).join(', ');
/* Store the 'real' root slide number for use during slide changes. */
$.each(slides, function(i, $el) {
var $parentSlides = $el.parentsUntil(opts.selectors.container, slideTest);
$el.data('rootSlide', $parentSlides.length ?
$parentSlides.last().data('rootSlide') :
rootIndex++
);
});
$(opts.selectors.statusTotal).text(rootIndex - 1);
}
// Find where we started in the deck and set initial state
$.each(slides, function(i, $el) {
if ($el === $current) {
ndx = i;
return false;
}
});
updateCurrent(null, ndx, ndx);
})
/* Update current slide number with each change event */
.bind('deck.change', updateCurrent);
})(jQuery, 'deck');

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
if(!this.sh_languages){this.sh_languages={}}sh_languages.cpp=[[[/(\b(?:class|struct|typename))([ \t]+)([A-Za-z0-9_]+)/g,["sh_keyword","sh_normal","sh_classname"],-1],[/\b(?:class|const_cast|delete|dynamic_cast|explicit|false|friend|inline|mutable|namespace|new|operator|private|protected|public|reinterpret_cast|static_cast|template|this|throw|true|try|typeid|typename|using|virtual)\b/g,"sh_keyword",-1],[/\/\/\//g,"sh_comment",1],[/\/\//g,"sh_comment",7],[/\/\*\*/g,"sh_comment",8],[/\/\*/g,"sh_comment",9],[/(\bstruct)([ \t]+)([A-Za-z0-9_]+)/g,["sh_keyword","sh_normal","sh_classname"],-1],[/^[ \t]*#(?:[ \t]*include)/g,"sh_preproc",10,1],[/^[ \t]*#(?:[ \t]*[A-Za-z0-9_]*)/g,"sh_preproc",-1],[/\b[+-]?(?:(?:0x[A-Fa-f0-9]+)|(?:(?:[\d]*\.)?[\d]+(?:[eE][+-]?[\d]+)?))u?(?:(?:int(?:8|16|32|64))|L)?\b/g,"sh_number",-1],[/"/g,"sh_string",13],[/'/g,"sh_string",14],[/\b(?:__asm|__cdecl|__declspec|__export|__far16|__fastcall|__fortran|__import|__pascal|__rtti|__stdcall|_asm|_cdecl|__except|_export|_far16|_fastcall|__finally|_fortran|_import|_pascal|_stdcall|__thread|__try|asm|auto|break|case|catch|cdecl|const|continue|default|do|else|enum|extern|for|goto|if|pascal|register|return|sizeof|static|struct|switch|typedef|union|volatile|while)\b/g,"sh_keyword",-1],[/\b(?:bool|char|double|float|int|long|short|signed|unsigned|void|wchar_t)\b/g,"sh_type",-1],[/~|!|%|\^|\*|\(|\)|-|\+|=|\[|\]|\\|:|;|,|\.|\/|\?|&|<|>|\|/g,"sh_symbol",-1],[/\{|\}/g,"sh_cbracket",-1],[/(?:[A-Za-z]|_)[A-Za-z0-9_]*(?=[ \t]*\()/g,"sh_function",-1],[/([A-Za-z](?:[^`~!@#$%&*()_=+{}|;:",<.>\/?'\\[\]\^\-\s]|[_])*)((?:<.*>)?)(\s+(?=[*&]*[A-Za-z][^`~!@#$%&*()_=+{}|;:",<.>\/?'\\[\]\^\-\s]*\s*[`~!@#$%&*()_=+{}|;:",<.>\/?'\\[\]\^\-\[\]]+))/g,["sh_usertype","sh_usertype","sh_normal"],-1]],[[/$/g,null,-2],[/(?:<?)[A-Za-z0-9_\.\/\-_~]+@[A-Za-z0-9_\.\/\-_~]+(?:>?)|(?:<?)[A-Za-z0-9_]+:\/\/[A-Za-z0-9_\.\/\-_~]+(?:>?)/g,"sh_url",-1],[/<\?xml/g,"sh_preproc",2,1],[/<!DOCTYPE/g,"sh_preproc",4,1],[/<!--/g,"sh_comment",5],[/<(?:\/)?[A-Za-z](?:[A-Za-z0-9_:.-]*)(?:\/)?>/g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z](?:[A-Za-z0-9_:.-]*)/g,"sh_keyword",6,1],[/&(?:[A-Za-z0-9]+);/g,"sh_preproc",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*(?:\/)?>/g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*/g,"sh_keyword",6,1],[/@[A-Za-z]+/g,"sh_type",-1],[/(?:TODO|FIXME|BUG)(?:[:]?)/g,"sh_todo",-1]],[[/\?>/g,"sh_preproc",-2],[/([^=" \t>]+)([ \t]*)(=?)/g,["sh_type","sh_normal","sh_symbol"],-1],[/"/g,"sh_string",3]],[[/\\(?:\\|")/g,null,-1],[/"/g,"sh_string",-2]],[[/>/g,"sh_preproc",-2],[/([^=" \t>]+)([ \t]*)(=?)/g,["sh_type","sh_normal","sh_symbol"],-1],[/"/g,"sh_string",3]],[[/-->/g,"sh_comment",-2],[/<!--/g,"sh_comment",5]],[[/(?:\/)?>/g,"sh_keyword",-2],[/([^=" \t>]+)([ \t]*)(=?)/g,["sh_type","sh_normal","sh_symbol"],-1],[/"/g,"sh_string",3]],[[/$/g,null,-2]],[[/\*\//g,"sh_comment",-2],[/(?:<?)[A-Za-z0-9_\.\/\-_~]+@[A-Za-z0-9_\.\/\-_~]+(?:>?)|(?:<?)[A-Za-z0-9_]+:\/\/[A-Za-z0-9_\.\/\-_~]+(?:>?)/g,"sh_url",-1],[/<\?xml/g,"sh_preproc",2,1],[/<!DOCTYPE/g,"sh_preproc",4,1],[/<!--/g,"sh_comment",5],[/<(?:\/)?[A-Za-z](?:[A-Za-z0-9_:.-]*)(?:\/)?>/g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z](?:[A-Za-z0-9_:.-]*)/g,"sh_keyword",6,1],[/&(?:[A-Za-z0-9]+);/g,"sh_preproc",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*(?:\/)?>/g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*/g,"sh_keyword",6,1],[/@[A-Za-z]+/g,"sh_type",-1],[/(?:TODO|FIXME|BUG)(?:[:]?)/g,"sh_todo",-1]],[[/\*\//g,"sh_comment",-2],[/(?:<?)[A-Za-z0-9_\.\/\-_~]+@[A-Za-z0-9_\.\/\-_~]+(?:>?)|(?:<?)[A-Za-z0-9_]+:\/\/[A-Za-z0-9_\.\/\-_~]+(?:>?)/g,"sh_url",-1],[/(?:TODO|FIXME|BUG)(?:[:]?)/g,"sh_todo",-1]],[[/$/g,null,-2],[/</g,"sh_string",11],[/"/g,"sh_string",12],[/\/\/\//g,"sh_comment",1],[/\/\//g,"sh_comment",7],[/\/\*\*/g,"sh_comment",8],[/\/\*/g,"sh_comment",9]],[[/$/g,null,-2],[/>/g,"sh_string",-2]],[[/$/g,null,-2],[/\\(?:\\|")/g,null,-1],[/"/g,"sh_string",-2]],[[/"/g,"sh_string",-2],[/\\./g,"sh_specialchar",-1]],[[/'/g,"sh_string",-2],[/\\./g,"sh_specialchar",-1]]];

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,35 @@
# include <mpi.h>
# include <stdio.h>
# include <string.h>
int main(int argc, char **argv)
{
int rank, size;
char someString[] = "Can haz cheezburgerz?";
MPI_Init(&argc, &argv);
MPI_Comm_rank( MPI_COMM_WORLD, & rank );
MPI_Comm_size( MPI_COMM_WORLD, & size );
if ( rank == 0 )
{
int n = 42;
int i;
for( i = 1; i < size; ++i)
{
MPI_Send( &n, 1, MPI_INT, i, 0, MPI_COMM_WORLD );
MPI_Send( &someString, strlen( someString )+1, MPI_CHAR, i, 0, MPI_COMM_WORLD );
}
} else {
char buffer[ 128 ];
int received;
MPI_Status stat;
MPI_Recv( &received, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &stat );
printf( "[Worker] Number : %d\n", received );
MPI_Recv( buffer, 128, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &stat );
printf( "[Worker] String : %s\n", buffer );
}
MPI_Finalize();
}

12
tutorial/eo/README Executable file
View file

@ -0,0 +1,12 @@
Eo Tutorial - corresponding to EO version 0.9.1+
To start the tutorial, read index.html in your favorite browser.
Many things are missing, including many solutions for the exercises,
the introduction to EC and most of the Component-based pages.
More important, all examples of this tutorial have only been tested
on a Linux computer, and the Makefile will not work with MS-Windows
systems. Any help is welcome!
Be patient ...
evoMarc

View file

@ -0,0 +1,45 @@
######################################################################################
### 1) Include the sources
######################################################################################
INCLUDE_DIRECTORIES(${MyStruct_SOURCE_DIR}/src)
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src)
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/do)
######################################################################################
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
IF(NOT WIN32 OR CYGWIN)
LINK_DIRECTORIES(${EO_BINARY_DIR}/lib)
ENDIF(NOT WIN32 OR CYGWIN)
# especially for Visual Studio
IF(WIN32 AND NOT CYGWIN)
LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE})
ENDIF(WIN32 AND NOT CYGWIN)
######################################################################################
######################################################################################
### 3) Define your targets
######################################################################################
ADD_EXECUTABLE(MyStructEA MyStructEA.cpp)
######################################################################################
######################################################################################
### 4) Link the librairies for the targets
######################################################################################
TARGET_LINK_LIBRARIES(MyStructEA eo eoutils ga es)
######################################################################################

View file

@ -0,0 +1,40 @@
######################################################################################
### 1) Main project config
######################################################################################
# set the project name
PROJECT(MyStructEA)
# set a language for the entire project.
ENABLE_LANGUAGE(CXX)
#####################################################################################
######################################################################################
### 2) We need to know where EO is installed
######################################################################################
IF(NOT EO_SOURCE_DIR)
SET( EO_SOURCE_DIR
EO_SRC_DIR CACHE STRING
"EO source directory"
FORCE)
ENDIF(NOT EO_SOURCE_DIR)
IF(NOT EO_BINARY_DIR)
SET( EO_BINARY_DIR
EO_BIN_DIR CACHE STRING
"EO binary directory"
FORCE)
ENDIF(NOT EO_BINARY_DIR)
######################################################################################
######################################################################################
### 3) Where must cmake go now ?
######################################################################################
SUBDIRS(src)
######################################################################################

48
tutorial/eo/Templates/ChangeLog Executable file
View file

@ -0,0 +1,48 @@
2007-02-22 Jochen Küpper <jochen@fhi-berlin.mpg.de>
* mutation.tmpl, quadCrossover.tmpl, stat.tmpl: Initialize
formerly uninitialized variables.
* README.tmpl: Hint to regular Templates/README for details.
* README: Add documentation for adding new source-files.
* Makefile.am.src-tmpl (noinst_HEADERS): Add
(MyStruct_SOURCES): Move header files from here to the new
noinst_HEADERS variable.
2007-01-16 Jochen Küpper <jochen@fhi-berlin.mpg.de>
* README: Add instructions for bash.
2007-01-14 Jochen Küpper <jochen@fhi-berlin.mpg.de>
* createEOproject.sh: Set TargetDir to /tmp/<name>. This is a workaround
for automake finding the scripts of eo itself if we run it in a embedded
subdirectory.
(COPYING, INSTALL): create.
* README: State more explicitly what a "complete installation" means.
Give build-instructions for moved directories.
2006-12-16 Jochen Küpper <jochen@fhi-berlin.mpg.de>
* Makefile.am (EXTRA_DIST): Distribute exactly the necessary files
* EO.tpl, MyStructEA.cpp, MyStructSEA.cpp, make_MyStruct.cpp: Use
correct names for includes.
* README.manual: This is a copy of the old README.
* README: Describe the new way and setup of creating a new EO project.
* createEOproject.sh, Makefile.am.src-tmpl, Makefile.am.top-tmpl:
* configure.ac.tmpl: New files to create a standalone EO project from
templates.
* Local Variables:
* coding: iso-8859-1
* mode: flyspell
* fill-column: 80
* End:

938
tutorial/eo/Templates/EO.tpl Executable file
View file

@ -0,0 +1,938 @@
\TEMPLATE_START// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEA.cpp
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
//
// Main file for creating a new representation in EO
// =================================================
//
// This main file includes all other files that have been generated by the
// script create.sh, so it is the only file to compile.
//
// In case you want to build up a separate library for your new Evolving Object,
// you'll need some work - follow what's done in the src/ga dir, used in the
// main file BitEA in tutorial/Lesson4 dir.
// Or you can wait until we do it :-)
// Miscellany includes and declarations
#include <iostream>
using namespace std;
// eo general include
#include "eo"
// real bounds (not yet in general eo include)
#include "utils/eoRealVectorBounds.h"
unsigned *pCurrentGeneration;
unsigned *pEZ_NB_GEN;
double EZ_MUT_PROB, EZ_XOVER_PROB, EZ_REPL_PERC=0.0;
int EZ_NB_GEN, EZ_POP_SIZE;
unsigned long EZ_NB_EVALUATIONS=0L;
inline int random(int b1=0, int b2=1){
return rng.random(b2-b1)+b1;
}
inline double random(double b1=0, double b2=1){
return rng.uniform(b2-b1)+b1;
}
inline float random(float b1=0, float b2=1){
return rng.uniform(b2-b1)+b1;
}
\ANALYSE_PARAMETERS
\INSERT_USER_DECLARATIONS
\INSERT_INITIALISATION_FUNCTION
// include here whatever specific files for your representation
// Basically, this should include at least the following
/** definition of representation:
* class EASEAGenome MUST derive from EO<FitT> for some fitness
*/
#include "EASEAGenome.h"
// GENOTYPE EASEAGenome ***MUST*** be templatized over the fitness
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// START fitness type: double or eoMaximizingFitness if you are maximizing
// eoMinimizingFitness if you are minimizing
typedef \MINIMAXI MyFitT ; // type of fitness
// END fitness type
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Then define your EO objects using that fitness type
typedef EASEAGenome<MyFitT> Indi; // ***MUST*** derive from EO
\INSERT_USER_FUNCTIONS
/** definition of evaluation:
* class EASEAEvalFunc MUST derive from eoEvalFunc<EASEAGenome>
* and should test for validity before doing any computation
* see tutorial/Templates/evalFunc.tmpl
*/
#include "EASEAEvalFunc.h"
/** definition of initialization:
* class EASEAGenomeInit MUST derive from eoInit<EASEAGenome>
*/
#include "EASEAInit.h"
/** include all files defining variation operator classes
*/
#include "EASEAMutation.h"
#include "EASEAQuadCrossover.h"
// Use existing modules to define representation independent routines
// These are parser-based definitions of objects
// how to initialize the population
// it IS representation independent if an eoInit is given
#include <make_pop.h>
eoPop<Indi >& make_pop(eoParser& _parser, eoState& _state, eoInit<Indi> & _init){
return do_make_pop(_parser, _state, _init);
}
// the stopping criterion
#include "make_continue.h"
eoContinue<Indi>& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval){
return do_make_continue(_parser, _state, _eval);
}
// outputs (stats, population dumps, ...)
#include <make_checkpoint.h>
eoCheckPoint<Indi>& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi>& _eval, eoContinue<Indi>& _continue) {
return do_make_checkpoint(_parser, _state, _eval, _continue);
}
// evolution engine (selection and replacement)
#include <make_algo_easea.h>
eoAlgo<Indi>& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<Indi>& _eval, eoContinue<Indi>& _continue, eoGenOp<Indi>& _op){
return do_make_algo_scalar(_parser, _state, _eval, _continue, _op);
}
// simple call to the algo. stays there for consistency reasons
// no template for that one
#include <make_run.h>
// the instanciating fitnesses
#include <eoScalarFitness.h>
void run_ea(eoAlgo<Indi>& _ga, eoPop<Indi>& _pop){
do_run(_ga, _pop);
}
// checks for help demand, and writes the status file
// and make_help; in libutils
void make_help(eoParser & _parser);
// now use all of the above, + representation dependent things
int main(int argc, char* argv[]){
try {
\INSERT_INIT_FCT_CALL
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
// The fitness
//////////////
EASEAEvalFunc<Indi> plainEval/* (varType _anyVariable) */;
// turn that object into an evaluation counter
eoEvalFuncCounter<Indi> eval(plainEval);
// a genotype initializer
EASEAInit<Indi> init;
// or, if you need some parameters, you might as well
// - write a constructor of the eoMyStructInit that uses a parser
// - call it from here:
// eoEASEAInit<Indi> init(parser);
// Build the variation operator (any seq/prop construct)
// here, a simple example with only 1 crossover (2->2, a QuadOp) and
// one mutation, is given.
// Hints to have choice among multiple crossovers and mutations are given
// A (first) crossover (possibly use the parser in its Ctor)
EASEAQuadCrossover<Indi> cross /* (eoParser parser) */;
// IF MORE THAN ONE:
// read its relative rate in the combination
// double cross1Rate = parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value();
// create the combined operator with the first one (rename it cross1 !!!)
// eoPropCombinedQuadOp<Indi> cross(cross1, cross1Rate);
// and as many as you want the following way:
// 1- write the new class by mimicking eoEASEAQuadCrossover.h
// 2- include that file here together with eoEASEAQuadCrossover above
// 3- uncomment and duplicate the following lines:
//
// eoEASEASecondCrossover<Indi> cross2(eoParser parser);
// double cross2Rate = parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value();
// cross.add(cross2, cross2Rate);
// NOTE: if you want some gentle output, the last one shoudl be like
// cross.add(cross, crossXXXRate, true);
/////////////// Same thing for MUTATION
// a (first) mutation (possibly use the parser in its Ctor)
EASEAMutation<Indi> mut /* (eoParser parser) */;
// IF MORE THAN ONE:
// read its relative rate in the combination
// double mut1Rate = parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value();
// create the combined operator with the first one (rename it cross1 !!!)
// eoPropCombinedMonOp<Indi> mut(mut1, mut1Rate);
// and as many as you want the following way:
// 1- write the new class by mimicking eoEASEAMutation.h
// 2- include that file here together with eoEASEAMutation above
// 3- uncomment and duplicate the following lines:
//
// eoEASEASecondMutation<Indi> mut2(eoParser parser);
// double mut2Rate = parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value();
// mut.add(mut2, mut2Rate);
// NOTE: if you want some gentle output, the last one shoudl be like
// mut.add(mut, mutXXXRate, true);
// now encapsulate your crossover(s) and mutation(s) into an eoGeneralOp
// so you can fully benefit of the existing evolution engines
// First read the individual level parameters
double pCross = parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ).value();
// minimum check
if ( (pCross < 0) || (pCross > 1) )
throw runtime_error("Invalid pCross");
double pMut = parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ).value();
// minimum check
if ( (pMut < 0) || (pMut > 1) )
throw runtime_error("Invalid pMut");
// now create the generalOp
eoSGAGenOp<Indi> op(cross, pCross, mut, pMut);
//// Now the representation-independent things
//
// YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT
// unless you want to add specific statistics to the checkpoint
//////////////////////////////////////////////
// initialize the population
// yes, this is representation indepedent once you have an eoInit
eoPop<Indi>& pop = make_pop(parser, state, init);
// give popSize to AESAE control
EZ_POP_SIZE = pop.size();
// stopping criteria
eoContinue<Indi> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<Indi> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<Indi>& ga = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorithm
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<Indi>(eval, pop);
// if you want to print it out
// cout << "Initial Population\n";
// pop.sortedPrintOn(cout);
// cout << endl;
run_ea(ga, pop); // run the ga
cout << "Best individual in final population\n";
cout << pop.best_element() << endl;
}
catch(exception& e)
{
cout << e.what() << endl;
}
return 0;
}
\START_EO_GENOME_H_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEAGenome.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
#ifndef _EASEAGenome_h
#define _EASEAGenome_h
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
* Note that you MUST derive your structure from EO<fitT>
* but you MAY use some other already prepared class in the hierarchy
* like eoVector for instance, if you handle a vector of something....
* If you create a structure from scratch,
* the only thing you need to provide are
* a default constructor
* IO routines printOn and readFrom
*
* Note that operator<< and operator>> are defined at EO level
* using these routines
*/
\ANALYSE_USER_CLASSES
\INSERT_USER_CLASSES
template< class FitT>
class EASEAGenome: public EO<FitT> {
public:
/** Ctor: you MUST provide a default ctor.
* though such individuals will generally be processed
* by some eoInit object
*/
EASEAGenome() : EO<FitT>()
{
// START Code of default Ctor of an EASEAGenome object
\GENOME_CTOR
// END Code of default Ctor of an EASEAGenome object
}
EASEAGenome(const EASEAGenome & arg) : EO<FitT>()
{
\GENOME_CTOR
copy(arg);
}
virtual ~EASEAGenome()
{
// START Code of Destructor of an EASEAGenome object
\GENOME_DTOR
// END Code of Destructor of an EASEAGenome object
}
virtual string className() const { return "EASEAGenome"; }
EASEAGenome& operator=(const EASEAGenome & arg) {
copy(arg);
return *this;
}
void copy(const EASEAGenome& genome)
{
if(&genome != this){
\GENOME_DTOR
\COPY_CTOR
if (genome.invalid()) { // copying an invalid genome
fitness(FitT()); // put a valid value (i.e. non NAN)
invalidate(); // but INVALIDATE the genome
}
else
fitness(genome.fitness());
}
}
bool operator==(const EASEAGenome & genome) const {
\EQUAL
return true;
}
bool operator!=(const EASEAGenome & genome) const {
return !(*this==genome);
}
/** printing... */
void printOn(ostream& os) const
{
// First write the fitness
EO<FitT>::printOn(os);
os << ' ';
// START Code of default output
/** HINTS
* in EO we systematically write the sizes of things before the things
* so readFrom is easier to code (see below)
*/
\INSERT_DISPLAY
\WRITE
// END Code of default output
}
/** reading...
* of course, your readFrom must be able to read what printOn writes!!!
*/
void readFrom(istream& is)
{
// of course you should read the fitness first!
EO<FitT>::readFrom(is);
// START Code of input
/** HINTS
* remember the EASEAGenome object will come from the default ctor
* this is why having the sizes written out is useful
*/
\READ
// END Code of input
}
//private: // put all data here - no privacy in EASEA
// START Private data of an EASEAGenome object
\INSERT_GENOME
// END Private data of an EASEAGenome object
};
#endif
\START_EO_EVAL_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEAEvalFunc.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
/*
Evaluator in EO: a functor that computes the fitness of an EO
=============================================================
*/
#ifndef _EASEAEvalFunc_h
#define _EASEAEvalFunc_h
// include whatever general include you need
#include <stdexcept>
#include <fstream>
// include the base definition of eoEvalFunc
#include "eoEvalFunc.h"
/**
Always write a comment in this format before class definition
if you want the class to be documented by Doxygen
*/
template <class EOT>
class EASEAEvalFunc : public eoEvalFunc<EOT>
{
public:
/// Ctor - no requirement
// START eventually add or modify the anyVariable argument
EASEAEvalFunc()
// EASEAEvalFunc( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an EASEAEvalFunc object
// END Code of Ctor of an EASEAEvalFunc object
}
/** Actually compute the fitness
*
* @param EOT & _eo the EO object to evaluate
* it should stay templatized to be usable
* with any fitness type
*/
void operator()(EOT & genome)
{
// test for invalid to avoid recomputing fitness of unmodified individuals
if (genome.invalid())
{
// START Code of computation of fitness of the EASEA object
\INSERT_EVALUATOR
// END Code of computation of fitness of the EASEA object
}
}
private:
// START Private data of an EASEAEvalFunc object
// varType anyVariable; // for example ...
// END Private data of an EASEAEvalFunc object
};
#endif
\START_EO_INITER_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEAInit.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
/*
objects initialization in EO
============================
*/
#ifndef _EASEAInit_h
#define _EASEAInit_h
// include the base definition of eoInit
#include <eoInit.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* There is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO (e.g. to initialize
* atoms of an eoVector you will need an eoInit<AtomType>)
*/
template <class GenotypeT>
class EASEAInit: public eoInit<GenotypeT> {
public:
/// Ctor - no requirement
// START eventually add or modify the anyVariable argument
EASEAInit()
// EASEAInit( varType & _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an EASEAInit object
// END Code of Ctor of an EASEAInit object
}
/** initialize a genotype
*
* @param _genotype generally a genotype that has been default-constructed
* whatever it contains will be lost
*/
void operator()(GenotypeT & _genotype)
{
// START Code of random initialization of an EASEAGenome object
\INSERT_EO_INITIALISER
// END Code of random initialization of an EASEAGenome object
_genotype.invalidate(); // IMPORTANT in case the _genotype is old
}
private:
// START Private data of an EASEAInit object
// varType & anyVariable; // for example ...
// END Private data of an EASEAInit object
};
#endif
\START_EO_MUT_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEAMutation.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
/*
simple mutation operators
=========================
*/
#ifndef EASEAMutation_H
#define EASEAMutation_H
#include <eoOp.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* THere is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO
*/
template<class GenotypeT>
class EASEAMutation: public eoMonOp<GenotypeT>
{
public:
/**
* Ctor - no requirement
*/
// START eventually add or modify the anyVariable argument
EASEAMutation()
// EASEAMutation( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an EASEAMutation object
// END Code of Ctor of an EASEAMutation object
}
/// The class name. Used to display statistics
string className() const { return "EASEAMutation"; }
/**
* modifies the parent
* @param _genotype The parent genotype (will be modified)
*/
bool operator()(GenotypeT & _genotype)
{
// START code for mutation of the _genotype object
\INSERT_MUTATOR
// END code for mutation of the _genotype object
private:
// START Private data of an EASEAMutation object
// varType anyVariable; // for example ...
// END Private data of an EASEAMutation object
};
#endif
\START_EO_QUAD_XOVER_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEAQuadCrossover.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
/*
Template for simple quadratic crossover operators
=================================================
Quadratic crossover operators modify both genotypes
*/
#ifndef EASEAQuadCrossover_H
#define EASEAQuadCrossover_H
#include <eoOp.h>
/**
* Always write a comment in this format before class definition
* if you want the class to be documented by Doxygen
*
* THere is NO ASSUMPTION on the class GenoypeT.
* In particular, it does not need to derive from EO
*/
template<class GenotypeT>
class EASEAQuadCrossover: public eoQuadOp<GenotypeT>
{
public:
/**
* Ctor - no requirement
*/
// START eventually add or modify the anyVariable argument
EASEAQuadCrossover()
// EASEAQuadCrossover( varType _anyVariable) : anyVariable(_anyVariable)
// END eventually add or modify the anyVariable argument
{
// START Code of Ctor of an EASEAQuadCrossover object
// END Code of Ctor of an EASEAQuadCrossover object
}
/// The class name. Used to display statistics
string className() const { return "EASEAQuadCrossover"; }
/**
* eoQuad crossover - modifies both genotypes
*/
bool operator()(GenotypeT& child1, GenotypeT & child2)
{
GenotypeT parent1(child1);
GenotypeT parent2(child2);
// START code for crossover of child1 and child2 objects
\INSERT_CROSSOVER
return (parent1!=child1)||(parent2!=child2);
// END code for crossover of child1 and child2 objects
}
private:
// START Private data of an EASEAQuadCrossover object
// varType anyVariable; // for example ...
// END Private data of an EASEAQuadCrossover object
};
#endif
\START_EO_CONTINUE_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*-
//
// (The above line is useful in Emacs-like editors)
//
//*************************************
//
// EASEA_make_continue.h
//
// C++ file generated by AESAE-EO v0.7
//
//*************************************
//
#ifndef _make_continue_h
#define _make_continue_h
/*
Contains the templatized version of parser-based choice of stopping criterion
It can then be instantiated, and compiled on its own for a given EOType
(see e.g. in dir ga, ga.cpp)
*/
// Continuators - all include eoContinue.h
#include <eoCombinedContinue.h>
#include <eoGenContinue.h>
#include <eoSteadyFitContinue.h>
#include <eoEvalContinue.h>
#include <eoFitContinue.h>
#ifndef _MSC_VER
#include <eoCtrlCContinue.h> // CtrlC handling (using 2 global variables!)
#endif
// also need the parser and param includes
#include <utils/eoParser.h>
#include <utils/eoState.h>
/////////////////// the stopping criterion ////////////////
template <class Indi>
eoCombinedContinue<Indi> * make_combinedContinue(eoCombinedContinue<Indi> *_combined, eoContinue<Indi> *_cont)
{
if (_combined) // already exists
_combined->add(*_cont);
else
_combined = new eoCombinedContinue<Indi>(*_cont);
return _combined;
}
template <class Indi>
eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval)
{
//////////// Stopping criterion ///////////////////
// the combined continue - to be filled
eoCombinedContinue<Indi> *continuator = NULL;
// for each possible criterion, check if wanted, otherwise do nothing
// First the eoGenContinue - need a default value so you can run blind
// but we also need to be able to avoid it <--> 0
eoValueParam<unsigned>& maxGenParam = _parser.createParam(\NB_GEN, "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion");
// and give control to EASEA
EZ_NB_GEN = maxGenParam.value();
pEZ_NB_GEN = & maxGenParam.value();
// do not test for positivity in EASEA
// if (maxGenParam.value()) // positive: -> define and store
// {
eoGenContinue<Indi> *genCont = new eoGenContinue<Indi>(maxGenParam.value());
_state.storeFunctor(genCont);
// and "add" to combined
continuator = make_combinedContinue<Indi>(continuator, genCont);
// }
// the steadyGen continue - only if user imput
eoValueParam<unsigned>& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion");
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
if (_parser.isItThere(steadyGenParam))
{
eoSteadyFitContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
(minGenParam.value(), steadyGenParam.value());
// store
_state.storeFunctor(steadyCont);
// add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, steadyCont);
}
// Same thing with Eval - but here default value is 0
eoValueParam<unsigned long>& maxEvalParam = _parser.createParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)",'E',"Stopping criterion");
if (maxEvalParam.value()) // positive: -> define and store
{
eoEvalContinue<Indi> *evalCont = new eoEvalContinue<Indi>(_eval, maxEvalParam.value());
_state.storeFunctor(evalCont);
// and "add" to combined
continuator = make_combinedContinue<Indi>(continuator, evalCont);
}
/*
// the steadyEval continue - only if user imput
eoValueParam<unsigned>& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion");
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
if (_parser.isItThere(steadyGenParam))
{
eoSteadyGenContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
(minGenParam.value(), steadyGenParam.value());
// store
_state.storeFunctor(steadyCont);
// add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, steadyCont);
}
*/
// the target fitness
eoFitContinue<Indi> *fitCont;
eoValueParam<double>& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion");
if (_parser.isItThere(targetFitnessParam))
{
fitCont = new eoFitContinue<Indi>
(targetFitnessParam.value());
// store
_state.storeFunctor(fitCont);
// add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, fitCont);
}
#ifndef _MSC_VER
// the CtrlC interception (Linux only I'm afraid)
eoCtrlCContinue<Indi> *ctrlCCont;
eoValueParam<bool>& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion");
if (_parser.isItThere(ctrlCParam))
{
ctrlCCont = new eoCtrlCContinue<Indi>;
// store
_state.storeFunctor(ctrlCCont);
// add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, ctrlCCont);
}
#endif
// now check that there is at least one!
if (!continuator)
throw runtime_error("You MUST provide a stopping criterion");
// OK, it's there: store in the eoState
_state.storeFunctor(continuator);
// and return
return *continuator;
}
#endif
\START_EO_PARAM_TPL#*************************************
#
# EASEA.prm
#
# Parameter file generated by AESAE-EO v0.7
#
#*************************************
###### General ######
# --help=0 # -h : Prints this message
# --stopOnUnknownParam=1 # Stop if unknown param entered
--seed=0 # -S : Random number seed
###### Evolution Engine ######
--popSize=\POP_SIZE # -P : Population Size
--selection=\SELECTOR\SELECT_PRM # -S : Selection: Roulette, Ranking(p,e), DetTour(T), StochTour(t) or Sequential(ordered/unordered)
--nbOffspring=\OFF_SIZE # -O : Nb of offspring (percentage or absolute)
--replacement=General # Type of replacement: Generational, ESComma, ESPlus, SSGA(T), EP(T)
###### Evolution Engine / Replacement ######
--elite=\ELITE_SIZE # Nb of elite parents (percentage or absolute)
--eliteType=\ELITISM # Strong (true) or weak (false) elitism (set elite to 0 for none)
--surviveParents=\SURV_PAR_SIZE # Nb of surviving parents (percentage or absolute)
--reduceParents=\RED_PAR\RED_PAR_PRM # Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform
--surviveOffspring=\SURV_OFF_SIZE # Nb of surviving offspring (percentage or absolute)
--reduceOffspring=\RED_OFF\RED_OFF_PRM # Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform
--reduceFinal=\RED_FINAL\RED_FINAL_PRM # Final reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform
###### Output ######
# --useEval=1 # Use nb of eval. as counter (vs nb of gen.)
# --useTime=1 # Display time (s) every generation
# --printBestStat=1 # Print Best/avg/stdev every gen.
# --printPop=0 # Print sorted pop. every gen.
###### Output - Disk ######
# --resDir=Res # Directory to store DISK outputs
# --eraseDir=1 # erase files in dirName if any
# --fileBestStat=0 # Output bes/avg/std to file
###### Output - Graphical ######
# --plotBestStat=0 # Plot Best/avg Stat
# --plotHisto=0 # Plot histogram of fitnesses
###### Persistence ######
# --Load= # -L : A save file to restart from
# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.?
# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never)
# --saveTimeInterval=0 # Save every T seconds (0 or absent = never)
# --status=OneMaxGenomeEA.status # Status file
###### Stopping criterion ######
# --maxGen=100 # -G : Maximum number of generations () = none)
# --steadyGen=100 # -s : Number of generations with no improvement
# --minGen=0 # -g : Minimum number of generations
# --maxEval=0 # -E : Maximum number of evaluations (0 = none)
# --targetFitness=0 # -T : Stop when fitness reaches
# --CtrlC=0 # -C : Terminate current generation upon Ctrl C
###### Variation Operators ######
# --cross1Rate=1 # -1 : Relative rate for crossover 1
# --mut1Rate=1 # -1 : Relative rate for mutation 1
--pCross=\XOVER_PROB # -C : Probability of Crossover
--pMut=\MUT_PROB # -M : Probability of Mutation
\START_EO_MAKEFILE_TPL#*************************************
#
# EASEA.mak
#
# Makefile generated by AESAE-EO v0.7
#
#*************************************
# sample makefile for building an EA evolving a new genotype
DIR_EO = \EO_DIR
.cpp: ; c++ -DPACKAGE=\"eo\" -I. -I$(DIR_EO)/src -Wall -g -o $@ $*.cpp $(DIR_EO)/src/libeo.a $(DIR_EO)/src/utils/libeoutils.a
.cpp.o: ; c++ -DPACKAGE=\"eo\" -I. -I\EO_DIR/src -Wall -g -c $*.cpp
LIB_EO = $(DIR_EO)/src/utils/libeoutils.a $(DIR_EO)/src/libeo.a
SOURCES = EASEA.cpp \
EASEAEvalFunc.h \
EASEAGenome.h \
EASEAInit.h \
EASEAMutation.h \
EASEAQuadCrossover.h \
$(LIB_EO)
ALL = EASEA
EASEA : $(SOURCES)
c++ -g -I. -I$(DIR_EO)/src -o $@ EASEA.cpp $(LIB_EO) -lm
all : $(ALL)
clean : ; /bin/rm *.o $(ALL)
\TEMPLATE_END

View file

@ -0,0 +1,16 @@
bin_PROGRAMS = MyStruct
noinst_HEADERS = eoMyStruct.h \
eoMyStructEvalFunc.h \
eoMyStructInit.h \
eoMyStructMutation.h \
eoMyStructQuadCrossover.h
MyStruct_SOURCES = MyStructEA.cpp
dnl Local Variables:
dnl coding: iso-8859-1
dnl mode: makefile-automake
dnl fill-column: 80
dnl End:

View file

@ -0,0 +1,8 @@
SUBDIRS = src
dnl Local Variables:
dnl coding: iso-8859-1
dnl mode: makefile-automake
dnl fill-column: 80
dnl End:

Some files were not shown because too many files have changed in this diff Show more