Challenge

Week 4.1 - Genetic Algorithm

AIM:-To write the code in MATLAB to optimize the stalagmite function and find the global maxima of the function.

OBJECTIVE:-1.Explanation about the concept of a genetic algarithem.
2.Explanation of syntax for ga in matlab.
EQUATIONS;-

f1,x=[sin(5.1πx+0.5)]6f1,x=[sin⁡(5.1πx+0.5)]6

f1,y=[sin(5.1πy+0.5)]6f1,y=[sin⁡(5.1πy+0.5)]6

f2,x=exp[−4ln(2)(x−0.0667)20.64]f2,x=exp⁡[-4ln⁡(2)(x-0.0667)20.64]

f2,y=exp[−4ln(2)(y−0.0667)20.64]f2,y=exp⁡[-4ln⁡(2)(y-0.0667)20.64]

∴∴f(x,y)=f1,x×f1,y×f2,x×f2,y

THEORY:-Genetical Algorithem is a search heuristic that is inspired by Charles
Darwin theory of natural evaluation.
-This algorithem reflects the process of natural selection where fittest individuals are selected for reproduction to generate for next generation.
There are five phases in genetic algorithem and explained as below.
1.INITIAL POPULATION:-The problem intiates with a set of individuals which is called population.Each individual is a solution to the problem we want to slove.
-Each individual is characterized by a set of parameters called Genes.
-Genes are joined into a string which yields us chromosome which is nothing but a solution.
2.FITNESS FUNCTION;-The fitness function determines how fit an individual is.it gives a fitness score to each individual.
3.SELECTION PHASE:-The main objective of this phase is to select the fittest individual and let them pass their gene on to the next generation.
4.CROSSOVER:-For each pair of parents to be mated.crossover point is chosen at random from within the genes.
-For example.consider the crossover point to be 3 as in the figure below.
5.MUTATION:-Muation is a random process where once the genes are replaced by another to produce a new genetic structure.

Syntax for defining ‘ga’ (Genetic Algorithm) in matlab –

The ‘ga’ syntax in matlab is used to find the minimum of function using genetic algorithm. There are several ways to define the ‘ga’ function depending on the problem being solved. The syntax used for this study is shown below.

  • x = ga(fun,nvars)

where,

x = optimal solution/variables;

fun = Objective function;

nvars = Number of variables;

Sometimes ‘[x,fval]’ is used instead of ‘x’ where ‘fval’ gives objective function value at the solution

  • x = ga(fun,nvars,A,B,Aeq,Beq,lb,ub)

where,

A, B = Linear inequality constraints

Aeq, Beq = Linear equality constraints

If there are no linear equalities and inequalities, then A, B, Aeq, Beq are set to ‘[ ]’.

  • x = ga(fun,nvars,A,B,Aeq,Beq,lb,ub,nonlcon,IntCon,options)

where,

nonlcon = Nonlinear constraints

IntCon = Integer Values

options = Optimization options

If there are no nonlinear constraints and integer values, the nonlcon and IntCon are set to ‘[ ]’.

clear all
close all
clc

% Defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);

% creating a 2Dimensional mesh
[xx yy] = meshgrid(x, y);

% Evalutingthe 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


 surfc(x,y,f)
xlabel('x value')
ylabel('y value')

shading interp

[inputs, fval] = ga(@stalagmite, 2)e

function code:-

function [f] = stalagmite(input_vector)
x=input_vector(1);
y=input_vector(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

MATLAB CODE:-2

clear all
close all
clc

x = linspace(0,0.6,150);
y = linspace(0,0.6,150);

num_cases = 50

% Creating 2 dimensional mesh
[xx, yy] = meshgrid(x,y);

% Evaluting 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 - Statictical 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')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')

% Study2 - Statistical behavier -with upper & lower bound)

tic
for i= 1:num_cases
    [inputs,fopt(i)] =ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6]);
            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('Unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')

% Study 3 -Increasing GA interations

options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',500);

tic

for i= 1:num_cases
    [inputs,fopt(i)] =ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6],[],[],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('Unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')

FUNCTION CODE:-

function [f] = stalagmite(input_vector)
x=input_vector(1);
y=input_vector(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

Here in this code,

  1. The code starts with clear all, close all and clc where,
  • ‘clear all’ command is used to clear the data stored in the workspace.
  • ‘close all’ command is used to close all plots and figures.
  • ‘clc’ command is used to clear the command window.
  1. Then the ‘x’ array and ‘y’ array is defined using ‘linspace’ command to create values at 150 equal intervals.
  2. A 2D mesh of x and y array is created by using ‘meshgrid’ command and the number of iterations or cases that the code should perform is defined. This is given by n = 50.
  3. To evaluate the stalagmite function, ‘for’ loop is used where ‘i’ is initialized and for every value of ‘i’ another ‘for’ loop is used to initialize ‘j’.
  4. The input vector values of ‘xx’ and ‘yy’ are defined and the stalagmite function for these input vector is defined. This will form a basic stalagmite function and we can plot it separately if needed.
  5. After preparing the inputs needed for the function, next step is to obtain the results for 3 cases of the genetic algorithm. In first case or study, the maximum value of function is found out with no restrictions, no bounds and no limits.
  6. This is done using ‘for’ loop where we use ‘ga’ syntax to give values for inputs and optimum max value. The stalagmite function is called in ‘ga’ syntax and number of variables ‘nvars’ are 2.
  7. To know the time that is taken to solve the loop for 50 iterations, ‘tic’ and ‘toc’ command is used before and after the loop respectively.
  8. Then the function created in the loop is plotted by using ‘surfc’ command for ‘xx, yy and function output’. To neglect the gridlines on the surface and obtain a smooth and clean plot, ‘shading interp’ command is used. The ‘subplot(2,1,1)’ is used to plot multiple plots on same figure which also divides figure in grid of 2x1 and axes to be placed at 1.
  9. The ‘plot3’ command plots the 3D points at ‘xopt, yopt and optimum value of function’ with ‘o’ shaped and red colour. The labels and title are then provided. Now in the same figure, the values of optimum function ‘fopt’ are plotted for 50 iterations.
  10. The results of the above case will be different for each time we run the program. To get same value each time, we need to restrict the program within specific bounds namely upper bound and lower bound. The procedure for coding and plottind this procedure is same as Study 1. The only difference is in the ‘ga’ syntax. This time the algorithm is provided lower limits and upper limits as [0;0] and [1;1] respectively.
  11. After plotting the results for Study 2 or the bounded case, it is observed that the results are not same every time the program terminates. A solution to this problem is to increase the number of cases or iterations.
  12. So for Study 3, the number of iterations are increased to 300. So for this study, the syntax, “options = optimoptions(‘SolverName’,’Name’,‘Value’)” is used which returns with named parameter ‘Populations’ with the altered values ‘300’.
  13. The syntax for ‘ga’ contains ‘option’ term and the rest of the code is same as for Study 1 and 2.

RESULTS/OUTPUT:-

CONCLUSION:-

The global maxima is calculated by population sizing and the plot orovide a visual context of the soluton and varities authencity of of the obtained value

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.