G
- The gene type this GA evaluates,C
- The result type (of the fitness function).public class GeneticAlgorithm<G extends Gene<?,G>,C extends Comparable<? super C>> extends Object
Factory<Genotype<?>>
,
and a fitness Function
. The Genotype
implements the
Factory
interface and can therefore be used as prototype for creating
the initial Population and for creating new random Genotypes.
public static void main(final String[] args) {
final Factory〈Genotype〈BitGene〉〉 gtf = Genotype.of(
BitChromosome.of(10, 0.5)
);
final Function〈Genotype〈BitGene〉 Double〉 ff = ...
final GeneticAlgorithm〈BitGene, Double〉
ga = new GeneticAlgorithm〈〉(gtf, ff, Optimize.MAXIMUM);
ga.setup();
ga.evolve(100);
System.out.println(ga.getBestPhenotype());
}
The genotype factory, gtf
, in the example above will create genotypes
which consists of one BitChromosome
with length 10. The one to zero
probability of the newly created genotypes is set to 0.5. The fitness function
is parametrized with a BitGene
and a Double
. That means
that the fitness function is calculating the fitness value as Double
.
The return type of the fitness function must be at least a Comparable
.
The GeneticAlgorithm
object is then created with the genotype factory
and the fitness function. In this example the GA tries to maximize the fitness
function. If you want to find the minimal value you have to change the optimize
parameter from Optimize.MAXIMUM
to Optimize.MINIMUM
. The
ga.setup()
call creates the initial population and calculates its
fitness value. Then the GA evolves 100 generations (ga.evolve(100)
)
an prints the best phenotype found so far onto the console.
public static void main(final String[] args) {
...
ga.setSelectors(new RouletteWheelSelector〈BitGene〉());
ga.setAlterers(
new SinglePointCrossover〈BitGene〉(0.1),
new Mutator〈BitGene〉(0.01)
);
ga.setup();
ga.evolve(100);
System.out.println(ga.getBestPhenotype());
}
setOffspringSelector
and setSurvivorSelector
methods. The alterers are concatenated, at
first the crossover (with probability 0.1) is performed and then the
chromosomes are mutated (with probability 0.01).
org.jenetics.util
package, supports native Java serialization
and XML serialization. For XML marshaling Jenetics internally uses
the XML support from the Javolution project.
// Writing the population to disk.
final File file = new File("population.xml");
IO.jaxb.write(ga.getPopulation(), file);
// Reading the population from disk.
Population〈DoubleGene, Double〉 population =
(Population〈DoubleGene, Double〉)IO.jaxb.read(file);
ga.setPopulation(population);
Alterer
,
Selector
Modifier and Type | Field and Description |
---|---|
static int |
DEFAULT_MAXIMAL_PHENOTYPE_AGE
The default maximal phenotype age of this GA:
|
static double |
DEFAULT_OFFSPRING_FRACTION
The default offspring fraction used by this GA.
|
static int |
DEFAULT_POPULATION_SIZE
The default population size used by this GA.
|
Constructor and Description |
---|
GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory,
Function<? super Genotype<G>,? extends C> fitnessFunction)
Create a new genetic algorithm.
|
GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory,
Function<? super Genotype<G>,? extends C> fitnessFunction,
Function<? super C,? extends C> fitnessScaler)
Create a new genetic algorithm.
|
GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory,
Function<? super Genotype<G>,? extends C> fitnessFunction,
Function<? super C,? extends C> fitnessScaler,
Optimize optimization)
Create a new genetic algorithm.
|
GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory,
Function<? super Genotype<G>,? extends C> fitnessFunction,
Optimize optimization)
Create a new genetic algorithm.
|
Modifier and Type | Method and Description |
---|---|
void |
evolve()
Evolve one generation.
|
void |
evolve(Function<? super Statistics<G,C>,Boolean> until)
Evolve the GA as long the given
Function returns true . |
void |
evolve(int generations)
Evolve the given number of
generations |
Alterer<G> |
getAlterer()
Return the currently used
Alterer of the GA. |
Phenotype<G,C> |
getBestPhenotype()
Return the best
Phenotype so far or null if the GA hasn't
been initialized yet. |
Statistics<G,C> |
getBestStatistics()
Return the statistics of the best phenotype.
|
Function<? super Genotype<G>,? extends C> |
getFitnessFunction()
Return the used fitness
Function of the GA. |
Function<? super C,? extends C> |
getFitnessScaler()
Return the currently used fitness scaler
Function of the GA. |
int |
getGeneration()
Return the current overall generation.
|
Factory<Genotype<G>> |
getGenotypeFactory()
Return the used genotype
Factory of the GA. |
Lock |
getLock()
If you are using the
GeneticAlgorithm in an threaded environment
and you want to change some of the GAs parameters you can use the returned
Lock to synchronize your parameter changes. |
int |
getMaximalPhenotypeAge()
Return the maximal age of the
Phenotype s. |
int |
getNumberOfInvalidPhenotypes()
Return the number of invalid phenotypes, so far.
|
int |
getNumberOfKilledPhenotypes()
Return the number of killed phenotypes, so far.
|
double |
getOffspringFraction()
Return the currently used offspring fraction of the GA.
|
Selector<G,C> |
getOffspringSelector()
Return the currently used offspring
Selector of the GA. |
Population<G,C> |
getPopulation()
Return a copy of the current population.
|
int |
getPopulationSize()
Return the desired population size of the GA.
|
Statistics<G,C> |
getStatistics()
|
Statistics.Calculator<G,C> |
getStatisticsCalculator()
Return the current statistics calculator.
|
Selector<G,C> |
getSurvivorSelector()
Return the currently used survivor
Selector of the GA. |
Statistics.Time |
getTimeStatistics()
Return the current time statistics of the GA.
|
boolean |
isInitialized()
|
void |
setAlterer(Alterer<G> alterer)
Set the alterer.
|
void |
setAlterers(Alterer<G>... alterers)
Set the given alterers.
|
void |
setFitnessScaler(Function<? super C,? extends C> scaler)
Set the currently used fitness scaler.
|
void |
setGenotypes(Collection<Genotype<G>> genotypes)
Set/change the population in form of a list of genotypes.
|
void |
setMaximalPhenotypeAge(int age)
Set the maximum age of the phenotypes in the population.
|
void |
setOffspringFraction(double offspringFraction)
Set the offspring fraction.
|
void |
setOffspringSelector(Selector<G,C> selector)
Set the offspring selector.
|
void |
setPopulation(Collection<Phenotype<G,C>> population)
Set the (initial) population in form of a list of phenotypes.
|
void |
setPopulationSize(int size)
Set the desired population size.
|
void |
setSelectors(Selector<G,C> selector)
Set both, the offspring selector and the survivor selector.
|
void |
setStatisticsCalculator(Statistics.Calculator<G,C> calculator)
Set the statistic calculator for this genetic algorithm instance.
|
void |
setSurvivorSelector(Selector<G,C> selector)
Set the survivor selector.
|
void |
setup()
Create the initial population of the GA.
|
void |
setup(Collection<Genotype<G>> genotypes)
Setting up the
GeneticAlgorithm with the given initial
population. |
String |
toString()
This method acquires the lock to ensure that the returned value is
consistent.
|
public static final int DEFAULT_POPULATION_SIZE
public static final int DEFAULT_MAXIMAL_PHENOTYPE_AGE
public static final double DEFAULT_OFFSPRING_FRACTION
public GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory, Function<? super Genotype<G>,? extends C> fitnessFunction, Function<? super C,? extends C> fitnessScaler, Optimize optimization)
genotypeFactory
- the genotype factory this GA is working with.fitnessFunction
- the fitness function this GA is using.fitnessScaler
- the fitness scaler this GA is using.optimization
- Determine whether this GA maximize or minimize the
fitness function.NullPointerException
- if one of the arguments is null
.public GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory, Function<? super Genotype<G>,? extends C> fitnessFunction)
genotypeFactory
- the genotype factory this GA is working with.fitnessFunction
- the fitness function this GA is using.NullPointerException
- if one of the arguments is null
.public GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory, Function<? super Genotype<G>,? extends C> fitnessFunction, Optimize optimization)
genotypeFactory
- the genotype factory this GA is working with.fitnessFunction
- the fitness function this GA is using.optimization
- Determine whether this GA maximize or minimize the
fitness function.NullPointerException
- if one of the arguments is null
.public GeneticAlgorithm(Factory<Genotype<G>> genotypeFactory, Function<? super Genotype<G>,? extends C> fitnessFunction, Function<? super C,? extends C> fitnessScaler)
genotypeFactory
- the genotype factory this GA is working with.fitnessFunction
- the fitness function this GA is using.fitnessScaler
- the fitness scaler this GA is using.NullPointerException
- if one of the arguments is null
.public void setup()
setPopulation(Collection)
or
setGenotypes(Collection)
) a random population is generated.IllegalStateException
- if called more than once.public void setup(Collection<Genotype<G>> genotypes)
GeneticAlgorithm
with the given initial
population. Subsequent calls to this method throw an IllegalStateException.
This method is similar to the setGenotypes(Collection)
and
setPopulation(Collection)
methods, but this method is required
to be called only once and before starting evaluation. It also calculates
the timing statistics when (calculating the fitness values for the given
genotypes.genotypes
- the initial population.IllegalStateException
- if called more than once.setGenotypes(Collection)
,
setPopulation(Collection)
public void evolve()
IllegalStateException
- if the setup()
method was not called first.public void evolve(int generations)
generations
generations
- the number of generations
to evolve.public void evolve(Function<? super Statistics<G,C>,Boolean> until)
Function
returns true
.until
- the predicate which defines the termination condition.NullPointerException
- if the given predicate is null
.termination
public boolean isInitialized()
true
if the setup()
method has already been called,
false
otherwise.public Lock getLock()
If you are using the GeneticAlgorithm
in an threaded environment
and you want to change some of the GAs parameters you can use the returned
Lock
to synchronize your parameter changes. The GA acquires the
lock at the begin of the setup()
and the evolve()
methods and releases it at the end of these methods.
final GeneticAlgorithm〈DoubleGene, Double〉 ga = ...
final Function〈GeneticAlgorithm〈?, ?〉, Boolean〉 until = ...
//Starting the GA in separate thread.
final Thread thread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() &&
!until.apply(ga))
{
if (ga.getGeneration() == 0) {
ga.setup();
} else {
ga.evolve();
}
}
}
});
thread.start();
//Changing the GA parameters outside the evolving thread. All parameters
//are changed before the next evolve step.
ga.getLock().lock();
try {
ga.setAlterer(new Mutation(0.02);
ga.setPopulationSize(55);
ga.setMaximalPhenotypeAge(30);
} finally {
ga.getLock().unlock();
}
ga.getLock().lock();
try {
final Statistics〈?, ?〉 statistics = ga.getStatistic();
final Function〈?, ?〉 scaler = ga.getFitnessScaler();
} finally {
ga.getLock().unlock();
}
statistics
and
scaler
where used together within the same evolve()
step.public Factory<Genotype<G>> getGenotypeFactory()
Factory
of the GA. The genotype factory
is used for creating the initial population and new, random individuals
when needed (as replacement for invalid and/or died genotypes).Factory
of the GA.public Function<? super Genotype<G>,? extends C> getFitnessFunction()
Return the used fitness Function
of the GA. The fitness function
is also an important part when modeling the GA. It takes a genotype as
argument and returns, at least, a Comparable object as result---the
fitness value. This allows the GA, respectively the selection operators,
to select the offspring- and survivor population. Some selectors have
stronger requirements to the fitness value than a Comparable, but this
constraints is checked by the Java type system at compile time.
class Id implements Function〈Genotype〈DoubleGene〉, Double〉 {
public Double apply(final Genotype〈DoubleGene〉 genotype) {
return genotype.getGene().getAllele();
}
}
Function
defines the kind of
genotype from which the fitness value is calculated and the second type
parameter determines the return type. As already mentioned, the return
type must implement the Comparable
interface.Function
of the GA.public void setFitnessScaler(Function<? super C,? extends C> scaler)
class Sqrt extends Function〈Double, Double〉 {
public Double apply(final Double value) {
return sqrt(value);
}
}
The listing above shows a fitness scaler which reduces the the raw-fitness to its square root. This gives weaker individuals a greater changes being selected and weakens the influence of super-individuals.
When using a fitness scaler you have to take care, that your scaler doesn't destroy your fitness value. This can be the case when your fitness value is negative and your fitness scaler squares the value. Trying to find the minimum will not work in this configuration.scaler
- The fitness scaler.NullPointerException
- if the scaler is null
.public Function<? super C,? extends C> getFitnessScaler()
Function
of the GA.Function
of the GA.public double getOffspringFraction()
public Selector<G,C> getOffspringSelector()
Selector
of the GA.Selector
of the GA.public Selector<G,C> getSurvivorSelector()
Selector
of the GA.Selector
of the GA.public Alterer<G> getAlterer()
Alterer
of the GA.Alterer
of the GA.public int getGeneration()
public int getMaximalPhenotypeAge()
Phenotype
s.Phenotype
s.public Phenotype<G,C> getBestPhenotype()
Phenotype
so far or null
if the GA hasn't
been initialized yet.Phenotype
so far or null
if the GA hasn't
been initialized yet.public Statistics<G,C> getStatistics()
Population
Statistics
or null
if the GA hasn't been initialized yet.public void setOffspringSelector(Selector<G,C> selector)
selector
- The offspring selector.NullPointerException,
- if the given selector is null.public void setSurvivorSelector(Selector<G,C> selector)
selector
- The survivor selector.NullPointerException,
- if the given selector is null.public void setSelectors(Selector<G,C> selector)
selector
- The selector for the offspring and the survivors.NullPointerException
- if the selector
is null
public void setOffspringFraction(double offspringFraction)
offspringFraction
- The offspring fraction.IllegalArgumentException
- if the offspring fraction is out of
range.public void setAlterer(Alterer<G> alterer)
alterer
- The alterer.NullPointerException
- if the alterer is null.@SafeVarargs public final void setAlterers(Alterer<G>... alterers)
alterers
- the alterers to set.NullPointerException
- if the alterers are null.public void setMaximalPhenotypeAge(int age)
age
- Maximal phenotype age.IllegalArgumentException
- if the age is smaller then one.public void setPopulationSize(int size)
size
- The population size.IllegalArgumentException
- if the population size is smaller than
one.public void setPopulation(Collection<Phenotype<G,C>> population)
population
- The list of phenotypes to set. The population size is
set to phenotype.size()
.NullPointerException
- if the population, or one of its element, is
null
.IllegalArgumentException
- it the population size is smaller than
one.setGenotypes(Collection)
,
setup(Collection)
public void setGenotypes(Collection<Genotype<G>> genotypes)
genotypes
- The list of genotypes to set. The population size is set
to genotypes.size()
.NullPointerException
- if the population, or one of its elements,
is null
s.IllegalArgumentException
- it the population size is smaller than
one.setPopulation(Collection)
,
setup(Collection)
public Population<G,C> getPopulation()
public int getPopulationSize()
public Statistics<G,C> getBestStatistics()
null
if the algorithms hasn't been initialized.null
if the GA
hasn't been initialized yet.public int getNumberOfKilledPhenotypes()
public int getNumberOfInvalidPhenotypes()
public void setStatisticsCalculator(Statistics.Calculator<G,C> calculator)
calculator
- the new statistic calculator.NullPointerException
- if the given calculator
is
null
.public Statistics.Calculator<G,C> getStatisticsCalculator()
public Statistics.Time getTimeStatistics()
© 2007-2014 Franz Wilhelmstötter (2014-03-07 19:35)