Week 4.1 - Genetic Algorithm
syntax for ga:-
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub)
where,
1) x = optimum solution
2) no_of_variables = Number of variables, specified as a positive integer.
3) A,b = Linear equality constraints
4) Aeq,beq = Linear equality constraints
5) lb,lb.ub = lower bonds, upper bounds
6) nonIcon = use for non linear constraints
7) IntCon = to get solution in integer
8) options = minimize with non default options
function [F] = stalagmite(input_vector)
x = input_vector(1);
y = input_vector(2);
f1_x = (sin(5.1*pi*x+0.5)).^6;
f1_y = (sin(5.1*pi*y+0.5)).^6;
f2_x = exp(-4*log(2)*((x-0.0667).^2)/0.64);
f2_y = exp(-4*log(2)*((y-0.0667).^2)/0.64);
[F] = -(f1_x.*f1_y.*f2_x.*f2_y);
end
%creating & y array
x = linspace(0,0.5,150);
y = linspace(0,0.5,150);
num_cases = 50;
%creating 2D mesh
[xx yy] = meshgrid(x,y);
%calculating the stalagmite function
for i = 1:length(xx)
for j = 1:length(yy)
a(1)=xx(i,j);
a(2)=yy(i,j);
f(i,j) = stalagmite(a);
end
end
%case 1- satistical 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
title('Unbounded inputs')
xlabel('x values')
ylabel('y values')
plot3(xopt,yopt,fopt,'Marker','o', 'MarkerSize',6, 'MarkerFaceColor', 'r')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('Function maximum')
%case 2- satistical behaviour with upper & lower bounds
for i = 1:num_cases
[input,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
title('bounded inputs')
xlabel('x values')
ylabel('y values')
plot3(xopt,yopt,fopt,'Marker','o', 'MarkerSize',6, 'MarkerFaceColor', 'r')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('Function maximum')
%case 3- increasing GA Iteration
options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',170)
tic
for i = 1:num_cases
[input,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.5;0.5],[],[],options);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
fopt = -fopt;
f = -f;
study3_time = toc
figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,f)
shading interp
xlabel('x values')
ylabel('y values')
plot3(xopt,yopt,fopt,'Marker','o', 'MarkerSize',6, 'MarkerFaceColor', 'r')
subplot(2,1,2)
plot(fopt)
xlabel('iterations')
ylabel('Function maximum')
max_value = fopt
stalagmite function code :
function [F] = stalagmite(a)
x = a(1);
y = a(2);
f1 = (sin((5.1*pi*x)+0.5)).^6;
f2 = (sin((5.1*pi*y)+0.5)).^6;
f3 = exp((-4*log(2)*((x-0.0667).^2))/(0.64));
f4 = exp((-4*log(2)*((y-0.0667).^2))/(0.64));
F = -(f1*f2*f3*f4);
end