Genetic algorithm using octave
Aim:
To Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function Clearly expalin the concept of genetic algorithm in your own words and also explain the syntax for 'ga' function in MATLAB
genetic algorithm:
A genetic algorithm is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution. This algorithm reflects the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.
Program:
clear all
close all
clc
% defining search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 40; % number of times ga runs
% creating a 2D mesh
[xx yy] = meshgrid(x,y);
% evaluating the stalagmite function
for i = 1:length(xx)
for j = 1:length(yy)
input_vector(1) = xx(i,j);
input_vector(2) = yy(i,j);
f(i,j) = stalagmite(input_vector);
end
end
% study 1 : statistical behaviour
tic
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite,2);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study1_time = toc
figure(1)
subplot(2,1,1)
hold on
surfc(xx, yy, -f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Unbounded inputs')
xlabel('X values')
ylabel('Y values')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')
% study 2 : statistical behaviour with upper and lower bounds
tic
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study2_time = toc
figure(2)
subplot(2,1,1)
hold on
surfc(xx, yy, -f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded inputs')
xlabel('X values')
ylabel('Y values')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')
% study 3 : increasing GA population size
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',450);
tic
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options)
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study3_time = toc
figure(3)
subplot(2,1,1)
hold on
surfc(xx, yy, -f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded inputs with different population size')
xlabel('X values')
ylabel('Y values')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')
Stalagmite function:
% stalagmite function
function [output] = stalagmite(input_vector)
a = input_vector(1);
b = input_vector(2);
f1x = (sin(5.1*pi*a+0.5))^6;
f1y = (sin(5.1*pi*b+0.5))^6;
f2x = exp(-4*log(2)*(a-0.0667)^2/0.64);
f2y = exp(-4*log(2)*(b-0.0667)^2/0.64);
[output] = -(f1x*f2x*f1y*f2y);
end
Result:
thus the genetic algorithm programming is done ad output is obtained