ARITIFICAL INTELLIGENCE CODING IS IN JAVA //Generic algo package ga; public clas
ID: 3732088 • Letter: A
Question
ARITIFICAL INTELLIGENCE
CODING IS IN JAVA
//Generic algo
package ga;
public class GeneticAlgorithm {
protected int mPopulationSize;
protected int mTournamentsSize;
protected double mCrossoverProb;
protected double mMutationProb;
public GeneticAlgorithm(int populationSize,
int tournamentsSize, double crossoverProb, double mutationProb) {
mPopulationSize = populationSize;
mTournamentsSize = tournamentsSize;
mCrossoverProb = crossoverProb;
mMutationProb = mutationProb;
// ...
createInitialPopulation();
}
public void createInitialPopulation() {
// to be implemented
}
public void runOneGeneration() {
// to be implemented
}
public double getAverageFitness() {
// to be implemented; remove 0.0
return 0.0;
}
public double getBestFitness() {
// to be implemented; remove 0.0
return 0.0;
}
// other methods to be implemented
}
Description Your task is to implement a Genetic algorithm (GA) to find the maximum of the following function: 3 .3 where x and y are real numbers between -3 and 3. You can represent the problem variables as a chromosome by concatenating x and y as a binary string using 8-bits for each variable: 10 0010100 0l111 0 11 The calculation of x and y of a chromosome is done as follows: 1. A chromosome (string of 16 bits) is partitioned into two 8-bit strings 10 0 0 1 0 10and0 011 101 1 2. These strings are converted from binary (base 2) to decimal (base 10): (10001010)2 -Ix27 +0x26+0x25 +0x24 +1x23 +0x22+1x21 +0x20 138)10 and (0011 101)2-0x27 +0x26+lx25+lx24+1x23+0x22+1x21 +1x20 - (59)10Explanation / Answer
//GeneticAlgorithm.java
package ga;
import utils.*;
import java.util.*;
public class GeneticAlgorithm {
protected int mPopulationSize;
protected int mTournamentsSize;
protected double mCrossoverProb;
protected double mMutationProb;
protected ArrayList<Link> mNetwork;
private ArrayList<String> population;
private Random rand;
public GeneticAlgorithm(ArrayList<Link> network, int populationSize,
int tournamentsSize, double crossoverProb, double mutationProb) {
mNetwork = network;
mPopulationSize = populationSize;
mTournamentsSize = tournamentsSize;
mCrossoverProb = crossoverProb;
mMutationProb = mutationProb;
// ...
rand = new Random();
population = new ArrayList();
createInitialPopulation();
}
public void createInitialPopulation() {
for(int i = 0; i < mPopulationSize; i++){
StringBuilder chromosome = new StringBuilder();
for(int j = 0; j < mNetwork.size(); j++){
chromosome.append(rand.nextInt(2));
}
population.add(chromosome.toString());
}
}
public void printPopulation(){
for (String s:population){
System.out.println(s);
}
}
public void runOneGeneration() {
ArrayList<String> newPop = new ArrayList();
for(int i = 0; i < population.size(); i++){
if(newPop.size() < population.size()){
String s1 = tournamentSize(mTournamentsSize);
String s2 = tournamentSize(mTournamentsSize);
/*while(s1 == s2){
s2 = tournamentSize(mTournamentsSize);
}*/
String temp = crossOver(s1, s2);
String mTemp = mutate(temp);
newPop.add(mTemp);
}
}
population = newPop;
}
//red line
public double getAverageFitness() {
double avgFit = 0.0;
double testFit = 0.0;
for(String i : population){
testFit += Fitness.calculateFitnessOfOverlayNetwork(mNetwork, i);
}
avgFit = (testFit / population.size());
return avgFit;
}
//blue line
public double getBestFitness() {
double numeroUno = 0.0;
double testFit = 0.0;
for(String i : population){
testFit = Fitness.calculateFitnessOfOverlayNetwork(mNetwork, i);
if(testFit > numeroUno){
numeroUno = testFit;
}
}
return numeroUno;
}
public String tournamentSize(int size){
String bestChromosome = null;
double fitValue = 0.0;
ArrayList<Integer> used = new ArrayList();
for(int i = 0; i < size; i++){
int grab = rand.nextInt(population.size());
while(used.contains(grab)){
grab = rand.nextInt(population.size());
}
used.add(grab);
double currentFit = Fitness.calculateFitnessOfOverlayNetwork(mNetwork, population.get(grab));
if((fitValue < currentFit) || (bestChromosome == null)){
fitValue = currentFit;
bestChromosome = population.get(grab);
}
}
return bestChromosome;
}
public String crossOver(String parent1, String parent2){
StringBuilder toaster = new StringBuilder();
for(int i = 0; i < mNetwork.size(); i++){
double waffle = rand.nextDouble();
if(waffle > mCrossoverProb){
toaster.append(parent2.charAt(i));
}
else{
toaster.append(parent1.charAt(i));
}
}
String breakfast = toaster.toString();
return breakfast;
}
public String mutate(String testSubject){
StringBuilder madScientist = new StringBuilder();
for(int i = 0; i < testSubject.length(); i++){
double formula = rand.nextDouble();
if(formula <= mMutationProb){
if(testSubject.charAt(i) == '1'){
madScientist.append("0");
}
else{
madScientist.append("1");
}
}
else{
madScientist.append(testSubject.charAt(i));
}
}
String monster = madScientist.toString();
return monster;
}
}
====================================================================================
//RunGA.java
package main;
import java.io.IOException;
import java.util.*;
import javax.swing.SwingUtilities;
import utils.*;
import ga.GeneticAlgorithm;
public class RunGA {
@SuppressWarnings("unchecked")
public static void main(String args[]) {
int populationSize = 100;
int tournamentsSize = 2;
double crossoverProb = 0.7;
double mutationProb = 0.001;
int maxNumOfGenerations = 1000;
double bestFitness = 0.0;
ArrayList<Link> network = new ArrayList<Link>();
final double[] yBestFitness = new double[maxNumOfGenerations];
final double[] yAverageFitness = new double[maxNumOfGenerations];
// read file
FileHelper filehelper = new FileHelper();
String fileName = "network.txt";
try {
network = filehelper.readFile(fileName);
} catch (IOException e) {
e.printStackTrace();
}
// run GA
GeneticAlgorithm ga = new GeneticAlgorithm(network, populationSize,
tournamentsSize, crossoverProb, mutationProb);
yBestFitness[0] = ga.getBestFitness();
yAverageFitness[0] = ga.getAverageFitness();
for (int i = 0; i < maxNumOfGenerations; i++) {
double bestFitnessCurrentRound;
ga.runOneGeneration();
bestFitnessCurrentRound = ga.getBestFitness();
if (bestFitnessCurrentRound > bestFitness) {
bestFitness = bestFitnessCurrentRound;
}
yBestFitness[i] = bestFitness;
yAverageFitness[i] = ga.getAverageFitness();
}
System.out.println("Best overall fitness: " + ga.getBestFitness());
System.out.println("Average overall fitness: " + ga.getAverageFitness());
ga.printPopulation();
// plot graph
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Plot(yAverageFitness, yBestFitness).setVisible(true);
}
});
}
}
=========================================================================
//FileHelper.java
package utils;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
public class FileHelper {
@SuppressWarnings({ "resource", "unused" })
public ArrayList<Link> readFile(String fileName) throws IOException {
Scanner file = new Scanner(new FileReader(fileName));
ArrayList<Link> network = new ArrayList<Link>();
// read each line of text file
while (file.hasNextLine()) {
Link link = new Link();
int row = 0;
int col = 0;
for (int i = 0; i < 3; i++) {
if (col == 0) {
link.setNode1((int) file.nextInt());
}
if (col == 1) {
link.setNode2((int) file.nextInt());
}
if (col == 2) {
link.setCost((double) file.nextDouble());
}
col++;
}
//link.setActive(0);
col = 0;
row++;
network.add(link);
}
return network;
}
}
=================================================================================
//Fitness.java
package utils;
import java.util.ArrayList;
public class Fitness {
private static double fitness;
private static double cost;
private static double costCompleteNetwork;
public static double calculateFitnessOfOverlayNetwork(ArrayList<Link> network, String chromosome) {
fitness = 0.0;
cost = 0.0;
costCompleteNetwork = 0.0;
for (int i = 0; i < network.size(); i++) {
costCompleteNetwork += network.get(i).getCost();
if (chromosome.charAt(i) == '1') {
cost += network.get(i).getCost();
}
}
fitness = 1 - (cost / costCompleteNetwork);
return fitness;
}
}
========================================================================
//Link.java
package utils;
public class Link {
private int node1;
private int node2;
private double cost;
//private int active;
public void setNode1(int sNode1) {
node1 = sNode1;
}
public void setNode2(int sNode2) {
node2 = sNode2;
}
public void setCost(double sCost) {
cost = sCost;
}
/*public void setActive(int sActive) {
active = sActive;
}*/
public int getNode1() {
return node1;
}
public int getNode2() {
return node2;
}
public double getCost() {
return cost;
}
/*public int getActive() {
return active;
}*/
}
=================================================================================
//Plot.java
package utils;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
@SuppressWarnings("serial")
public class Plot extends JFrame {
public Plot(double[] avgValues, double[] bestValues) {
super("Genetic Algorithm");
JPanel chartPanel = createChartPanel(avgValues, bestValues);
add(chartPanel, BorderLayout.CENTER);
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private JPanel createChartPanel(double[] avgValues, double[] bestValues) {
String chartTitle = "Fitness Chart";
String xAxisLabel = "Generations";
String yAxisLabel = "Fitness Value";
XYDataset dataset = createDataset(avgValues, bestValues);
JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
xAxisLabel, yAxisLabel, dataset);
return new ChartPanel(chart);
}
private XYDataset createDataset(double[] avgValues, double[] bestValues) {
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Average Fitness");
XYSeries series2 = new XYSeries("Best Fitness");
for (int i = 0; i < avgValues.length; i++) {
series1.add(i, avgValues[i]);
series2.add(i, bestValues[i]);
}
dataset.addSeries(series1);
dataset.addSeries(series2);
return dataset;
}
}
=================================================================================
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.