Challenge

Week 4.1 - Genetic Algorithm

USED PLATFORM: Matlab R2021a

AIM: To optimize the stalagmite function to find the global maxima of the function.

OBJECTIVE: 1. Code to optimise the stalagmite function and find the global maxima of the function.

2. Concept of genetic algorithm and also explain the syntax for ga.

3. Plot graphs for all 3 studies and for F maximum vs no. of iterations.

GENETIC ALGORITHM: Genetic algorithm is a method of solving optimization with a natural selection for a constrained and unconstrained. The genetic algorithm repeatedly modifies a population of individual solutions. At each step, the genetic algorithm selects individuals at random from the current population to be parents and uses them to produce the children for the next generation. over successive generations, the population evolves toward an optimal solution. You can apply the genetic algorithm to solve a variety of optimization problems.

Selection rules: select the individuals, called parents that contribute to the population of the next generation.

Crossover rules: combine two parents to form children for the next generation.

Mutation rules: apply random changes to individual parents to form the children.

SYNTAX OF GA IN MATLAB-

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

Input Arguments of syntax-

'x' is the variable to store the output of the genetic algorithm.

'ga' is minimum of function using genetic algorithm.

'fun' is the function handle to call the function.

'A' is linear inequality constraints (real matrix)

'B' is linear inequality constraints (real vector)

'Aeq' is linear equality constraints (real matrix)

'Beq' is linear equality constraints (real vector)

'lb' is lower bound.

'ub' is upper bound.

'nonlcon' is nonlinear constraints

'Intcon' represents the integer constraint, such that the value of the function is an integer.

'options' used to provide the value of the default parameters used named parameters, if it is required to replace the default parameters. This is done by using the 'optimoptions'

GOVERNING EQUATION:

The following is the given stalagmite function for which we need to find the global maxima.

When we solve with above equation, by default find the minima. But in our case we have to find the maxima, so to find the maxima we made the function with negative symbol in the above equation. Find this at function code. This equation used in function is shown below for reference-

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

BODY OF CONTENT:

Function Code-

%making function for stalgmite equation

function [func]= stalagmite_func(input_vector)

%x & y are input variables
x=input_vector(1);
y=input_vector(2);

f1_x=(sin(5.1*3.14*x+0.5)).^6;
f1_y=(sin(5.1*3.14*y+0.5)).^6;

f2_x=exp(-4*0.6931.*(x-0.0667)^2/(0.64));
f2_y=exp(-4*0.6931.*(y-0.0667)^2/(0.64));

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

end

GA code-

Output (Plot) of GA -

% Code to optimise the stalagmite function and find the global maxima of the function

clear all %to clean workspace
close all %to terminate all open plots
clc %to clean up pervious data from command window

x= linspace(0,0.6,150); % Assinging evenly spaced 150 row vector in variable x in b/w 0 to 0.6
y= linspace(0,0.6,150);% Assinging evenly spaced 150 row vector in variable y in b/w 0 to 0.6

[a,b]=meshgrid(x,y); % preparing 2D grid coordinates from above mentions variable x & y.

% Looping the value to each coordinate from a & b, to repeat the cycle one by one with the help of for loop.
for i=1:length(a) %assigning the length of largest array in i
    for j=1:length(b) %assigning the length of largest array in j
        %calling stalagmite function as stalagmite_func(input_vector). Refer function code explanation for more clarification.
        input_vector(1)=a(i,j); 
        input_vector(2)=b(i,j);
        f(i,j)=stalagmite_func(input_vector);
    end
end

surfc(a,b,-f)%to get a plot as a surface.
shading interp %to remove the grid-like structure in the plot, and color filling is done. Refer to Fig(1)
xlabel('X Axis') %to naming the axes
ylabel('Y Axis') %to naming the axes
title('Optimise the stalagmite function for global maxima') %assigning title to the plot

[x,fval] = ga(@stalagmite_func,2); %ga command is used. In the ga command, we call the stalagmite function and here we have two variables x and y so we enter it as 2.

Code for 3 studies and for F maximum vs no. of iterations-

% 3 studies and for F maximum vs no. of iterations

%Study 1- Statistical behaviour for GA.
clear all %to clean workspace
close all %to terminate all open plots
clc %to clean up pervious data from command window

% To assigning evenly spaced 150 rewo vector b/w 0 to 0.6
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);

[a,b]=meshgrid(x,y); % preparing 2D grid coordinates from above mentions variable x & y.

% Looping the value to each coordinate from a & b, to repeat the cycle one by one with the help of for loop.
for i=1:length(a) %assigning the length of largest array in i
    for j=1:length(b) %assigning the length of largest array in j
        %calling stalagmite function as stalagmite_func(input_vector). Refer function code explanation for more clarification.
        input_vector(1)=a(i,j); 
        input_vector(2)=b(i,j);
        f(i,j)=stalagmite_func(input_vector);
    end
end
num_cases=50; %To repeat and calculate the GA value 50 times.

tic %to record the current time to run the code 
% Assigning variable called k where storing data from 1 to num_cases each single valve at a time
for k=1:num_cases; %length of for loop set as a num_cases, one for each time.
    [inputs,fopt(k)]=ga(@stalagmite_func,2); % To calling the function stalagmite_func and number of variable in the function
%   To calculate x & y value and storing it in xopt and yopt.
    xopt(k)=inputs(1);
    yopt(k)=inputs(2);
end 
study_time1=toc %Recorded value is used to calculate the time taken by the code to run.

figure(2)% To defining the ploting fame
subplot(2,3,1) % Number of plots to be made in a single frame
hold on % To retain the previous plot
surfc(x,y,-f)%to get a plot as a surface. Negative sign is used to plot the invert the graph for viewing, as to find maxima negative sign is used in the function code.
shading interp %to remove the grid-like structure in the plot, and color filling is done. Refer to Fig(2)
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r') % to plot the stored values of xopt, yopt, and calculated points of function as fopt. Maximum value as a dot-like structure by using the marker opting and marker size.
title('Unbounded value')%assigning title to the plot
xlabel('X Axis') %to naming the axes
ylabel('Y Axis') %to naming the axes
subplot(2,3,4) % Number of plots to be made in a single frame
plot(fopt) % To plot the fopt points iteration vs function minimum
xlabel('Iteration')%to naming the axes
ylabel('Function minimum')%to naming the axes


%Study 2- Statistical behaviour with upper & lower bound limits-

tic %to record the current time to run the code 
% Assigning variable called k where storing data from 1 to num_cases each single valve at a time
for k=1:num_cases; %length of for loop set as a num_cases, one for each time.
    %Here we call stalgmite function only for upper & lower boundries. The lower boundary limit is set as 0,0 and the upper boundary limit is set as 1,1
    [inputs,fopt(k)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[1;1]);
    xopt(k)=inputs(1);
    yopt(k)=inputs(2);
end 
study_time2=toc %Recorded value is used to calculate the time taken by the code to run.

subplot(2,3,2) % Number of plots to be made in a single frame
hold on % To retain the previous plot
surfc(x,y,-f) %to get a plot as a surface. Negative sign is used to plot the invert the graph for viewing, as to find maxima negative sign is used in the function code.
shading interp %to remove the grid-like structure in the plot, and color filling is done. Refer to Fig(2) 
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')% to plot the stored values of xopt, yopt, and calculated points of function as fopt. Maximum value as a dot-like structure by using the marker opting and marker size.
title('Bounded value with upper & lower bound')%assigning title to the plot
xlabel('X Axis') %to naming the axes
ylabel('Y Axis') %to naming the axes
subplot(2,3,5) % Number of plots to be made in a single frame
plot(fopt) % To plot the fopt points iteration vs function minimum
xlabel('Iteration')%to naming the axes
ylabel('Function minimum')%to naming the axes

%Study-3 Increasing GA iterations
%to set the initial population size we use the optimoptions command and in that we mention the options, population size.
options=optimoptions('ga');
options=optimoptions(options,'populationsize',300);

tic %to record the current time to run the code 
% Assigning variable called k where storing data from 1 to num_cases each single valve at a time
for k=1:num_cases; %length of for loop set as a num_cases, one for each time.
    [inputs,fopt(k)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[1;1],[],[],options);
    xopt(k)=inputs(1);
    yopt(k)=inputs(2);
end 
study_time3=toc %Recorded value is used to calculate the time taken by the code to run.

subplot(2,3,3)% Number of plots to be made in a single frame
hold on % To retain the previous plot
surfc(x,y,-f) %to get a plot as a surface. Negative sign is used to plot the invert the graph for viewing, as to find maxima negative sign is used in the function code.
shading interp %to remove the grid-like structure in the plot, and color filling is done. Refer to Fig(2) 
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')% to plot the stored values of xopt, yopt, and calculated points of function as fopt. Maximum value as a dot-like structure by using the marker opting and marker size.
title('Bounded input with modified population size')%assigning title to the plot
xlabel('X Axis') %to naming the axes
ylabel('Y Axis') %to naming the axes
subplot(2,3,6)% Number of plots to be made in a single frame
plot(fopt) % To plot the fopt points iteration vs function minimum
xlabel('Iteration')%to naming the axes
ylabel('Function minimum')%to naming the axes

Output (Plot) of all 3 studies -

Result-

ERROR FACING WHILE CODING:

code for meshgrid was wrong due to which graph was not plotted-

Incorrect- a=meshgrid(x,y);

b=meshgrid(x,y);

Correct- [a,b]=meshgrid(x,y);

Others are typo error which was corrected.

CONCLUSION:

  • Understand how optimization technique is used with the ga command.
  • Understand the function of ga and it uses.
  • Understand how to improve our program step by step through different studies.

REFERENCES:

https://in.mathworks.com/help/gads/what-is-the-genetic-algorithm.html#:~:text=The%20genetic%20algorithm%20is%20a,a%20population%20of%20individual%20solutions.

https://en.wikipedia.org/wiki/Genetic_algorithm

https://www.tutorialspoint.com/genetic_algorithms/index.htm

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.