Skip to content

Commit

Permalink
Merge 4b094b2 into 3a5cf27
Browse files Browse the repository at this point in the history
  • Loading branch information
avijitbasak committed Sep 27, 2021
2 parents 3a5cf27 + 4b094b2 commit 1f03fcc
Show file tree
Hide file tree
Showing 130 changed files with 9,075 additions and 0 deletions.
@@ -0,0 +1,44 @@
<!--
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>
<groupId>org.apache.commons</groupId>
<artifactId>examples-ga</artifactId>
<version>4.0-SNAPSHOT</version>
</parent>
<artifactId>examples-ga-math-functions</artifactId>

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

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

</project>
@@ -0,0 +1,64 @@
/*
* 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.ga.mathfunctions;

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

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

/** 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 + "]";
}

}
@@ -0,0 +1,51 @@
/*
* 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.ga.mathfunctions;

import java.util.List;

import org.apache.commons.math4.ga.chromosome.AbstractListChromosome;
import org.apache.commons.math4.ga.chromosome.BinaryChromosome;
import org.apache.commons.math4.ga.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) {
final BinaryChromosome<Coordinate> binaryChromosome = (BinaryChromosome<Coordinate>) chromosome;
final List<Integer> alleles = binaryChromosome.getRepresentation();

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

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);
}

}
@@ -0,0 +1,40 @@
/*
* 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.ga.mathfunctions;

import org.apache.commons.math4.ga.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) {
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);
}

}
@@ -0,0 +1,104 @@
/*
* 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.ga.mathfunctions;

import org.apache.commons.math4.ga.crossover.OnePointCrossover;
import org.apache.commons.math4.ga.convergencecond.UnchangedBestFitness;
import org.apache.commons.math4.examples.ga.mathfunctions.utils.Constants;
import org.apache.commons.math4.examples.ga.mathfunctions.utils.GraphPlotter;
import org.apache.commons.math4.ga.GeneticAlgorithm;
import org.apache.commons.math4.ga.chromosome.BinaryChromosome;
import org.apache.commons.math4.ga.chromosome.Chromosome;
import org.apache.commons.math4.ga.convergencecond.StoppingCondition;
import org.apache.commons.math4.ga.listener.ConvergenceListenerRegistry;
import org.apache.commons.math4.ga.listener.PopulationStatisticsLogger;
import org.apache.commons.math4.ga.mutation.BinaryMutation;
import org.apache.commons.math4.ga.population.ListPopulation;
import org.apache.commons.math4.ga.population.Population;
import org.apache.commons.math4.ga.selection.TournamentSelection;
import org.apache.commons.math4.ga.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) {
final Population<Coordinate> initPopulation = getInitialPopulation();

final Dimension2FunctionOptimizer optimizer = new Dimension2FunctionOptimizer();

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
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
final StoppingCondition<Coordinate> stopCond = new UnchangedBestFitness<>(
Constants.GENERATION_COUNT_WITH_UNCHANGED_BEST_FUTNESS);

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

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

consoleLogger.log(bestFinal.toString());

}

/**
* Generates an initial population.
* @return initial population
*/
private static Population<Coordinate> getInitialPopulation() {
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,
fitnessFunction, decoder));
}
return population;
}

}

0 comments on commit 1f03fcc

Please sign in to comment.