Challenge

Week 4 - Genetic Algorithm

AIM:

To write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.

INTRODUCTION:

The genetic algorithm is based on theory of evolution proposed by Darwin. It is a technique of selecting the fittest individual from a population and then the offsprings will inherit the characteristics from the selected individuals. This process goes on and on for generations and in the end, a generation of fittest individuals will be obtained. In the same way, genetic algorithm works by selecting randomly from a population and over a period of generations, optimal solution is obtained.

Genetic algorithm finds application in optimization problems that are not easily solvable.

Three rules followed to come up with next generation:

Selection - Selecting the individuals randomly from a population.

Crossover - Combining two parents to form a child or children.

Mutation - Applying random changes to parents to form children.

INPUT FUNCTION:

PROCEDURE:

1. Two matrices x and y are defined using linspace command.

2. Number of cases is taken as 50.

3. The 'meshgrid' command is used to create a matrix from x and y.

4. A for loop is used to solve the genetic algorithm in 2D mesh grid.

5. Length of rows and columns are used as counters in the for loop.

6. ga function requires input vector. So, Stalagmite function is used to find elements in the mesh grid and the output is stored in a matrix.

7. The tic command is used to start the timer.

8. A for loop is used to extract the values of x and y for which the function value is minimum.

9. The format of ga function in Study 1:

[inputs,fopt] = ga(@func,nvar)

where

inputs - Values of x and y

fopt - Optimum function value

func - (here) Stalagmite function

nvar - Number of variables involved

10. The smallest value of the function in each iteration is stored in the fopt variable and its x and y coordinates in the inputs variable.

11. The toc command is used to stop the timer and time taken for the study is stored.

12. A subplot command is used to partition the plot into two rows and one column. The first plot is put in the first row.

13. The hold on command prevents the plot from being removed.

14. The surfc command is used to plot the surface contour with xx and yy value from the mesh grid. Negative of fopt is used to maximize the function.

15. The shading interp is used to smoothen the function and to remove the mesh grid lines.

16. The plot3 command helps in plotting a 3D point.

17. The second plot contains Function Maximum vs Number of Iterations which is in the second row.

18. The axis label and title are given to the plots.

19. The same procedure is carried out for the other two studies except varying the ga function in a certain way to bring the required output in the two cases.

20. The format for ga function in Study 2:

[inputs,fopt] = ga(@func, nvar, A, b, Aeq, beq, lb, ub)

where

A - Real matrix - Linear inequality constraints

b - Real vector - Linear inequality constraints

Aeq - Real matrix - Linear equality constraints

beq - Real vector - Linear equality constraints

lb - Lower bound (real vector or array)

ub - Upper bound (real vector or array)

The remaining are the same as in Study 1.

21. The format of ga function in Study 3:

[inputs,fopt[ = ga(@func, nvar, A, b, Aeq, beq, lb, ub, nonlcon, Intcon, options)

where

nonlcon - Non-linear constraints

Intcon - Integer variables specified as a vector of positive integers

options - Optimization options specified as the output of optimoptions or a structure

The remaining are the same as in Study 2.

22. The optimoptions is used to improve the accuracy by increasing the population size in Study 3.

23. To print results in the command window, fprintf command is used.

24. In Stalagmite function, the input vector is specified. The equations are substituted with inputs from mesh grid. Then a negative sign is used to maximize the function otherwise it will return the minimum value.

CODE:

MAIN PROGRAM:

% Genetic Algorithm
clear all
close all
clc

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

Num_cases = 50;

% 2D Mesh Creation
[xx,yy] = meshgrid(x,y);                                

% Stalagamite Function
for i = 1 : length(xx)
    for j = 1:length(yy)
        Input_value(1) = xx(i,j);
        Input_value(2) = yy(i,j);
        func(i,j) = Stalagmite(Input_value);
    end
end

% Statistical Behaviour (Unbounded)

% Timer Starts
tic

for i = 1 : Num_cases
    [Inputs_1,func_opt1(i)] = ga(@Stalagmite,2);
    xopt(i) = Inputs_1(1);
    yopt(i) = Inputs_1(2);
end

% Timer Ends
Study1_time = toc;                                  

figure(1)
subplot(2,1,1);                         % Creating a plot inside a plot
hold on;
surfc(xx,yy,-func);                     % Surface Contour

% Labelling Axis
xlabel('X Value');                      
ylabel('Y Value');                      
zlabel('Function Value');              

% Hiding Grid 
shading interp;

% Plotting the Results

% 3D Line Plot
plot3(xopt,yopt,-func_opt1,'Marker','o','MarkerSize',4,'MarkerFaceColor','r');
title('Statistical Behaviour (Unbounded)');         %Title to the plot

subplot(2,1,2);                                     %Plot inside a plot
plot(func_opt1);

% Labelling Axis
xlabel('Iterations');
ylabel('Function Maximum');

% Statistical Behaviour (Upper and Lower Bound)

% Timer Starts
tic

for i = 1:Num_cases
    [Inputs_2,func_opt2(i)] = ga(@Stalagmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(i) = Inputs_2(1);
    yopt(i) = Inputs_2(2);
end

% Timer Ends
Study2_time = toc;

figure(2)
subplot(2,1,1);                             % Plot inside a plot
hold on;
surfc(xx,yy,-func);                         % Surface Contour

% Labelling Axis
xlabel('X Value');
ylabel('Y Value');
zlabel('Function Value');

% Hiding Grid
shading interp;

% Plotting the Results
plot3(xopt,yopt,-func_opt2,'Marker','o','MarkerSize',4,'MarkerFaceColor','b');
title('Statistical Behaviour (Bounded)');

subplot(2,1,2);
plot(-func_opt2);
xlabel('Iterations');
ylabel('Function Maximum');

% Study 3
% Increasing GA Population Size
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',170);

% Timer Starts
tic

for i = 1:Num_cases
    [Inputs_3,func_opt3(i)] = ga(@Stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
    xopt(i) = Inputs_3(1);
    yopt(i) = Inputs_3(2);
end

% Timer Ends
Study3_time = toc;

figure(3)
subplot(2,1,1);
hold on;
surfc(xx,yy,-func);
xlabel('X Value');
ylabel('Y Value');
zlabel('Function Value');

shading interp;

% 3D Line Plot
plot3(xopt,yopt,-func_opt3,'Marker','o','MarkerSize',4,'MarkerFaceColor','g');
title('Statistical Behaviour (Bounded) with Increased Population Size');
subplot(2,1,2);
plot(-func_opt3);
xlabel('Iterations');
ylabel('Function Maximum');

% Total Time for the Whole Study
Total_time = Study1_time + Study2_time + Study3_time;

fprintf('\n The Results :');

fprintf('\n Study 1 : Statistical Behaviour (Unbounded)');
fprintf('\n The Time Taken for Study 1 is %f',Study1_time);
fprintf('\n The Coordinates of x and y for Global Maxima of the Function are %f and %f',Inputs_1(1),Inputs_1(2));
fprintf('\n The Global Maxima of the Function is %f',-(mean(func_opt1)));


fprintf('\n Study 2 : Statistical Behaviour (Upper and Lower Bound)');
fprintf('\n The Time Taken for Study 2 is %f',Study2_time);
fprintf('\n The Coordinates of x and y for Global Maxima of the Function are %f and %f',Inputs_2(1),Inputs_2(2));
fprintf('\n The Global Maxima of the Function is %f',-(mean(func_opt2)));


fprintf('\n Study 3 : Statistical Behaviour (Bounded) with Increased Population Size');
fprintf('\n The Time Taken for Study 3 is %f',Study3_time);
fprintf('\n The Coordinates of x and y for Global Maxima of the Function are %f and %f',Inputs_3(1),Inputs_3(2));
fprintf('\n The Global Maxima of the Function is %f',-(mean(func_opt3)));

fprintf('nn The Total Time Taken to Complete the Whole Study is %f',Total_time);  

STALAGMITE FUNCTION:

% Stalagmite Function

function [func] = Stalagmite(input_value)

f1_x = (sin(5.1*pi*input_value(1) + 0.5))^6;
f1_y = (sin(5.1*pi*input_value(2) + 0.5))^6;
f2_x = exp(-4*log(2)*(((input_value(1) - 0.0667)^2)/(0.64)));
f2_y = exp(-4*log(2)*(((input_value(2) - 0.0667)^2)/(0.64)));

func = -(f1_x*f1_y*f2_x*f2_y);

end

RESULTS:

STUDY 1:

STUDY 2:

STUDY 3:

OUTPUT FROM THE COMMAND WINDOW:

ERRORS:

1. 'func_opt' was typed as 'fun_opt' in a previous statement.

2. 'Study2_time' was typed as 'Study_time' at the end of timer 'toc'.

3. '%f' should have been there instead of '%' at the end and '\n' should be there at the beginning instead of 'nn'. 'fprintf' was also typed as 'fprint' which is an error.

These errors were rectified by visual inspection.

CONCLUSION:

Hence the genetic algorithm is performed to obtain the global maxima of Stalagmite function using MATLAB program.

REFERENCES:

1. https://in.mathworks.com/help/gads/how-the-genetic-algorithm-works.html

2. https://in.mathworks.com/help/gads/ga.html

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.

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.