Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoder #6

Merged
merged 2 commits into from
Sep 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to
You under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
Expand All @@ -25,20 +19,20 @@
</parent>
<artifactId>examples-genetics-math-functions</artifactId>

<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math4-genetics</artifactId>
<version>4.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.3</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

<!-- OSGi -->
<commons.osgi.symbolicName>org.apache.commons.math4.examples.genetics.mathfunctions</commons.osgi.symbolicName>
<commons.osgi.export>org.apache.commons.math4.examples.genetics.mathfunctions</commons.osgi.export>
<!-- Java 9+ -->
<commons.automatic.module.name>org.apache.commons.math4.examples.genetics.mathfunctions</commons.automatic.module.name>
<!-- Workaround to avoid duplicating config files. -->
<math.parent.dir>${basedir}/../../..</math.parent.dir>

<uberjar.name>examples-genetics-mathfunctions</uberjar.name>
<project.mainClass>org.apache.commons.math4.examples.genetics.mathfunctions.Dimension2FunctionOptimizer</project.mainClass>
</properties>

</project>
Original file line number Diff line number Diff line change
@@ -1,24 +1,61 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math4.examples.genetics.mathfunctions;

/**
* This class represents the coordinate of the problem domain i.e. the phenotype of chromosome.
*/
public class Coordinate {

private double x;
/** coordinate of first dimension. **/
private final double x;

private double y;
/** coordinate of second dimension. **/
private final double y;

/**
* constructor.
* @param x coordinate of first dimension
* @param y coordinate of second dimension
*/
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}

/**
* returns the coordinate of first dimension.
* @return coordinate of first dimension
*/
public double getX() {
return x;
}

/**
* returns the coordinate of second dimension.
* @return coordinate of second dimension
*/
public double getY() {
return y;
}

/**
* Returns a string representation of coordinate.
*/
@Override
public String toString() {
return "Coordinate [x=" + x + ", y=" + y + "]";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math4.examples.genetics.mathfunctions;

import java.util.List;

import org.apache.commons.math4.genetics.AbstractListChromosome;
import org.apache.commons.math4.genetics.BinaryChromosome;
import org.apache.commons.math4.genetics.chromosome.AbstractListChromosome;
import org.apache.commons.math4.genetics.chromosome.BinaryChromosome;
import org.apache.commons.math4.genetics.decoder.AbstractListChromosomeDecoder;

/**
* Decoder to convert chromosome's binary genotype to phenotype
* {@link Coordinate}.
*/
public class Dimension2Decoder extends AbstractListChromosomeDecoder<Integer, Coordinate> {

/**
* decode the binary representation of chromosome to {@link Coordinate}.
* @param chromosome The {@link AbstractListChromosome}
*/
@Override
protected Coordinate decode(AbstractListChromosome<Integer, Coordinate> chromosome) {
BinaryChromosome<Coordinate> binaryChromosome = (BinaryChromosome<Coordinate>) chromosome;
List<Integer> alleles = binaryChromosome.getRepresentation();
final BinaryChromosome<Coordinate> binaryChromosome = (BinaryChromosome<Coordinate>) chromosome;
final List<Integer> alleles = binaryChromosome.getRepresentation();

StringBuilder allelesStr = new StringBuilder();
final StringBuilder allelesStr = new StringBuilder();
for (Integer allele : alleles) {
allelesStr.append(Integer.toBinaryString(allele));
}

double x = Integer.parseInt(allelesStr.substring(0, 12), 2) / 100.0;
double y = Integer.parseInt(allelesStr.substring(12, 24), 2) / 100.0;
final double x = Integer.parseInt(allelesStr.substring(0, 12), 2) / 100.0;
final double y = Integer.parseInt(allelesStr.substring(12, 24), 2) / 100.0;

return new Coordinate(x, y);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,24 @@

package org.apache.commons.math4.examples.genetics.mathfunctions;

import org.apache.commons.math4.genetics.FitnessFunction;
import org.apache.commons.math4.genetics.fitness.FitnessFunction;

/**
* This class represents the mathematical fitness function for optimizing a 2
* dimension mathematical function.
*/
public class Dimension2FitnessFunction implements FitnessFunction<Coordinate> {

/**
* Computes the fitness value based on the decoded chromosome.
* @param coordinate The {@link Coordinate}
* @return the fitness value
*/
@Override
public double compute(Coordinate coordinate) {
double computedValue = Math.pow((Math.pow(coordinate.getX(), 2) + Math.pow(coordinate.getY(), 2)), .25) * (Math
.pow(Math.sin(50 * Math.pow((Math.pow(coordinate.getX(), 2) + Math.pow(coordinate.getY(), 2)), .1)), 2)
+ 1);
return -computedValue;
return -Math.pow(Math.pow(coordinate.getX(), 2) + Math.pow(coordinate.getY(), 2), .25) *
(Math.pow(Math.sin(50 * Math.pow(Math.pow(coordinate.getX(), 2) + Math.pow(coordinate.getY(), 2), .1)),
2) + 1);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,70 +18,86 @@
package org.apache.commons.math4.examples.genetics.mathfunctions;

import org.apache.commons.math4.examples.genetics.mathfunctions.utils.Constants;

import org.apache.commons.math4.examples.genetics.mathfunctions.utils.GraphPlotter;
import org.apache.commons.math4.genetics.BinaryChromosome;
import org.apache.commons.math4.genetics.Chromosome;
import org.apache.commons.math4.genetics.GeneticAlgorithm;
import org.apache.commons.math4.genetics.ListPopulation;
import org.apache.commons.math4.genetics.Population;
import org.apache.commons.math4.genetics.chromosome.BinaryChromosome;
import org.apache.commons.math4.genetics.chromosome.Chromosome;
import org.apache.commons.math4.genetics.convergencecond.StoppingCondition;
import org.apache.commons.math4.genetics.convergencecond.UnchangedBestFitness;
import org.apache.commons.math4.genetics.crossover.OnePointCrossover;
import org.apache.commons.math4.genetics.listener.ConvergenceListenerRegistry;
import org.apache.commons.math4.genetics.listener.PopulationStatisticsLogger;
import org.apache.commons.math4.genetics.mutation.BinaryMutation;
import org.apache.commons.math4.genetics.population.ListPopulation;
import org.apache.commons.math4.genetics.population.Population;
import org.apache.commons.math4.genetics.selection.TournamentSelection;
import org.apache.commons.math4.genetics.utils.ConsoleLogger;

/**
*
*
* This class represents an optimizer for a 2-dimensional math function using
* genetic algorithm.
*/
public class Dimension2FunctionOptimizer {

/**
* Optimizes the 2-dimension fitness function.
* @param args arguments
*/
public static void main(String[] args) {
Population<Coordinate> initPopulation = getInitialPopulation();
final Population<Coordinate> initPopulation = getInitialPopulation();

Dimension2FunctionOptimizer optimizer = new Dimension2FunctionOptimizer();
final Dimension2FunctionOptimizer optimizer = new Dimension2FunctionOptimizer();

ConvergenceListenerRegistry<Coordinate> convergenceListenerRegistry = ConvergenceListenerRegistry.getInstance();
convergenceListenerRegistry.addConvergenceListener(new PopulationStatisticsLogger<Coordinate>("UTF-8"));
final ConvergenceListenerRegistry<Coordinate> convergenceListenerRegistry = ConvergenceListenerRegistry
.getInstance();
convergenceListenerRegistry
.addConvergenceListener(new PopulationStatisticsLogger<Coordinate>(Constants.ENCODING));
convergenceListenerRegistry
.addConvergenceListener(new GraphPlotter("Convergence Stats", "generation", "fitness"));

optimizer.optimize(initPopulation);
}

/**
* Optimizes the population.
* @param initial The {@link Population}
*/
public void optimize(Population<Coordinate> initial) {

// initialize a new genetic algorithm
GeneticAlgorithm<Coordinate> ga = new GeneticAlgorithm<Coordinate>(new OnePointCrossover<Integer, Coordinate>(),
final GeneticAlgorithm<Coordinate> ga = new GeneticAlgorithm<>(new OnePointCrossover<Integer, Coordinate>(),
Constants.CROSSOVER_RATE, new BinaryMutation<Coordinate>(), Constants.AVERAGE_MUTATION_RATE,
new TournamentSelection<Coordinate>(Constants.TOURNAMENT_SIZE), Constants.ELITISM_RATE);

// stopping condition
StoppingCondition<Coordinate> stopCond = new UnchangedBestFitness<Coordinate>(
final StoppingCondition<Coordinate> stopCond = new UnchangedBestFitness<>(
Constants.GENERATION_COUNT_WITH_UNCHANGED_BEST_FUTNESS);

// run the algorithm
Population<Coordinate> finalPopulation = ga.evolve(initial, stopCond);
final Population<Coordinate> finalPopulation = ga.evolve(initial, stopCond);

// best chromosome from the final population
Chromosome<Coordinate> bestFinal = finalPopulation.getFittestChromosome();
ConsoleLogger consoleLogger = ConsoleLogger.getInstance("UTF-8");
final Chromosome<Coordinate> bestFinal = finalPopulation.getFittestChromosome();
final ConsoleLogger consoleLogger = ConsoleLogger.getInstance(Constants.ENCODING);
consoleLogger.log("*********************************************");
consoleLogger.log("***********Optimization Result***************");
consoleLogger.log("*********************************************");

consoleLogger.log(bestFinal.toString());

}

/**
* Generates an initial population.
* @return initial population
*/
private static Population<Coordinate> getInitialPopulation() {
Population<Coordinate> population = new ListPopulation<>(Constants.POPULATION_SIZE);
final Population<Coordinate> population = new ListPopulation<>(Constants.POPULATION_SIZE);
final Dimension2FitnessFunction fitnessFunction = new Dimension2FitnessFunction();
final Dimension2Decoder decoder = new Dimension2Decoder();
for (int i = 0; i < Constants.POPULATION_SIZE; i++) {
population.addChromosome(BinaryChromosome.<Coordinate>randomChromosome(Constants.CHROMOSOME_LENGTH,
new Dimension2FitnessFunction(), new Dimension2Decoder()));
fitnessFunction, decoder));
}
return population;
}
Expand Down