Challenge

Week 5 - Genetic Algorithm

# Solution:- Here we have to write a code to implement the stalagmite function and also find the global maxima of the function.

#OBJECTIVES :- The main objective of this report is to optimize the Stalagmite function by coding the program with help of genetic algorithm in MATLAB and explain the concept of Genetic algorithm and also explain the syntax of “ga"in MATLAB.

THEORY OF GENETIC ALGIORITHM:- The genetic algorithm is a technique for solving both constrained and unconstrained optimization problems that are based on natural selection, the process that drives biological evolution. The genetic algorithm constantly modifies the population size of individual solutions.

A genetic algorithm are commonly used to generate high-quality solutions to optimation and search problems by relying on biologically inspired operators such as mutations, crossover and selection . John Holland introduced genetic algorithm in 1960 based on the concept of Darwin’s theory Od evolution, and his student David E.Goldberg further extended GA in 1989.

Phases in Genetic Algoritham:-

A. Initialization of Population (Coding)

The code generates its random population of defined size and from that population the code evaluates the fitness of the members of the population according to which it forms new population based on no. of iterations performed.

1.Fitness Function

It is that function which we have to optimize and its optimization is done with the help of number of generations which have been formed by the code accordance with the fitness value of each member generated, these fitness values are used for the reproduction of the children

Selection

The idea of the selection phase is to select the fittest individuals and let them pass their genes to the next generation. The main goal of this phase is to find the region where the chances of getting the best solution are more.

Inspiration for this is from the survival of the fittest.

It should be a balance between exploration and exploitation of search space.

GA tries to move the genotype to higher fitness in the search space.

Too strong fitness selection bias can lead to sub-optimal solutions.

Too little fitness bias selection results in unfocused search

Reproduction

Generation of offspring happen in 2 way:

a. Crossover

b. Mutation

a. Crossover

Crossover is the most significant stage in the genetic algorithm. During crossover, a random point is selected while mating a pair of parents to generate offspring.

There are 3 major types of crossover.

Single Point Crossover:

A point on both parents’ chromosomes is picked randomly, and designated a ‘crossover point’.

Two-Point Crossover: Two crossover points are picked randomly from the parent chromosomes.

Unifofm Crossover: In a uniform crossover, typically, each bit is chosen from either parent with equal probability.

B. Mutation

In a few new offspring formed, some of their genes can be subjected to a mutation with a low random probability. This indicates that some of the bits in the bit chromosome can be flipped. Mutation happens to take care of diversity among the population and stop premature convergence.

Here we are going to procedure of Genetic algorithm:-

TERMINATION :-

  • The algorithm terminates if the population has converged. Then it is said that the genetic algorithm has provided the set of solution to our problem.
  • Using this approach of Genetic Algorithm we are going to optimize the stalagmite function and find the optimized value of stalagmite function.

GOVERNING EQUATION for Stalagmite function:

To generate the stalagmite function following function is used.

f1(x)=[sin⁡(5.1⋅π⋅x+0.5)]6">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)]6">f1(y)=[sin(5.1⋅π⋅y+0.5)]6f1(y)=[sin⁡(5.1⋅π⋅y+0.5)]6

f2(x)=exp(-4.log2.(x-0.0667)2)0.64">f2(x)=exp(−4.log2.(x−0.0667)2)0.64f2(x)=exp(-4.log2.(x-0.0667)2)0.64

f2(y)=exp(-4.log2.(y-0.0667)2)0.64">f2(y)=exp(−4.log2.(y−0.0667)2)0.64f2(y)=exp(-4.log2.(y-0.0667)2)0.64

f(x,y)=f1(x).f1(y).f2(x)〖.f〗2(y)">f(x,y)=f1(x).f1(y).f2(x)〖.f〗2(y)f(x,y)=f1(x).f1(y).f2(x)〖.f〗2(y)

Maximizing f (x,y) is the same as minimizing - f (x,y)

# The code for Stalagmite function in Matlab :-

function [f] = stalagmite_func(input_value)

x=input_value(1);

y=input_value(2);

f1x = (sin((5.1*pi*x) + 0.5)).^6;

f1y = (sin((5.1*pi*y) + 0.5)).^6;

f2x = exp(-4*log(2)*((x - 0.0667).^2)/(0.64));

f2y = exp(-4*log(2)*((y - 0.0667).^2)/(0.64));

f = -(f1x*f1y*f2x*f2y);

end

Stalactites are structures formed from mineral deposits that hang from caves. These formations hold tightly to the ceiling and hang down. As opposed to hanging from the ceiling, Stalagmite structures are formed from the cave floor that point upward. Stalagmite and Stalactite functions are mathematical functions which represents shapes similiar to that of the stalagmite and stalactite functions.

# Procedure for finding the maxima of the Function:-

  • Firstly, creating the mesh from the two vectors which will be acting as a search space to find the maxima of the function.
  • Creating the mesh of these two vectors using the ‘mesh’ command and defining the no. of iterations as num_cases to iterate the values of the optimum values of the function.
  • Now calculating the values of fitness function at each point of the mesh grid formed.
  • Now creating its surface through ‘surfc’ command which will also provide the contour of the generated surface.
  • While using surfc applying the -ve sign to the function will generate the surface upside down which will be quite good to get the maxima of the function, as it will provide positive value for the maxima using the -ve sign.

# Code Implementation for finding the global maxima of the function:-

function [f]= stalagmite(input_vector)

    x=input_vector(1);

    y=input_vector(2);
    
    f1x= (sin(5.1*pi*x + 0.5))^6;
    
    f1y= (sin(5.1*pi*y + 0.5))^6;
    
    f2x= exp((-4*log(2)*(x-0.0667)^2)/(0.64));
    
    f2y= exp((-4*log(2)*(y-0.0667)^2)/(0.64));
    
    f = -(f1x*f1y*f2x*f2y);

end

# Errors that we did during code writing-

Here I am unable to plot the contour plot with surface plot, than after reviewing the code and rearranging the command I am able to plot the final plot

# Driver code to compute the Global Maxima of this function using Genetic Algorithm:-

%Start Of the Program to find the global Maxima of the function

close all % close all the figure window
clear     % clearing all the variables from memory
clc       % clearing command window

x=linspace(0,0.6,150); % linspace command is used to generate linear space
y=linspace(0,0.6,150); % vector

%Creating 2D array using meshgrid function
[xx, yy]=meshgrid(x, y);

limit=100;  % for different number cases

% Nested for loop for array value input

for i=1:length(xx)  % outer for loop is used to run the counter for x
    for j=1:length(yy)% inner for loop is used to run the counter for y
        input_vector(1)=xx(i,j);% xx vector is assigned to input vector1
        input_vector(2)=yy(i,j);% xx vector is assigned to input vector2
        f(i,j)= stalagmite(input_vector);% stalagmite function is called
    end
end

% case 1 Unbounded Statistical Behaviour 
tic       % here tic stores the current time in timerVal  
for i=1:limit
    % here stalagmite function is assigned to genetic algorithm function
    [input1,fopt1(i)]=ga(@stalagmite,2);
    x_out(i)=input1(1);% input1 is assigned to x_output
    y_out(i)=input1(2);% input1 is assigned to y_output

end
% here toc function uses the recorded value to calculate the elapsed time
case_time_1=toc; 

figure(1) % assigned the figure 1
subplot(2,1,1) % subplot command is used to create axis in tiled position
surfc(xx, yy,-f); % surfc command is used to plot the contour suface plot
hold on
colorbar
shading interp % varies the color in each line segment and face  
% plot3 command is used for 3D plotting or line ploting
plot3(x_out,y_out,-fopt1,'marker','o','markersize',6,'markerfacecolor','r');
title('Case1(Unbounded Stastical data)','color','k')% title given
xlabel('x-value') % defining the x-axis
ylabel('y-value') % defining the y-axis
legend('Stalagmite Function','Global Maxima')% legend defined
grid on  % grid on command is used to create grid lines
subplot(2,1,2)% subplot command is used to create axis in tiled position
plot(-fopt1); % plotting optimum1 function
xlabel('No of Iterations') % xlabel is defined as no of iteration
ylabel('max Function Value')
 
% Case:-2. Stastical behaviour Bounded input 

tic         % here tic stores the current time in timerVal 
for i=1:limit
     % here stalagmite function is assigned to genetic algorithm function
    [input2,fopt2(i)]=ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6]);
    x_out(i)=input2(1);
    y_out(i)=input2(2);

end
case_time_2=toc;
% here toc function uses the recorded value to calculate the elapsed time
figure(2); % figure 2 defined
subplot(2,1,1) % subplot command is used to create axis in tiled position
hold on
surfc(xx,yy,-f) % surfc command is used to plot the contour suface plot
shading interp  % varies the color in each line segment and face
% plot3 command is used for 3D plotting or line ploting
plot3(x_out,y_out,-fopt2,'marker','o','markersize',6,'markerfacecolor','r');
title('case2 (Statistical bounded )','color','k') % title defined
xlabel('x-value')% x level defined
ylabel('y-value')% y level defined
grid on             % grid lined defined
subplot(2,1,2)% subplot command is used to create axis in tiled position
plot(-fopt2)     % plotting 2nd optimum function
xlabel('No Of Iterations') % x-level redefined
ylabel('max Function Value')% y level redefined

 % Case:3 Stastical behaviour with increased population size
options=optimoptions('ga');
options=optimoptions(options,'populationsize',300);
  
 tic         % here tic stores the current time in timerVal 
for i=1:limit
     % here stalagmite function is assigned to genetic algorithm function
    [input3, fopt3(i)]=ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6],[],[],options);
    x_out(i)=input3(1);
    y_out(i)=input3(2);

end

case_time_3=toc;
% here toc function uses the recorded value to calculate the elapsed time

figure(3)
subplot(2,1,1)% subplot command is used to create axis in tiled position
hold on
surfc(xx,yy,-f) % surfc command is used to plot the contour suface plot
shading interp  % varies the color in each line segment and face
colorbar
% plot3 command is used for 3D plotting or line ploting
plot3(x_out,y_out,-fopt3,'marker','o','markersize',6,'markerfacecolor','r')
title('Case3(increased population size)','color','k')% title defined
xlabel('x-value');          % x value defined
ylabel('y-value');          % y value defined
legend('Stalagmite Function','Maxima')% legend defined
grid on                     % grid on
subplot(2,1,2)% subplot command is used to create axis in tiled position
plot(-fopt3)                % plotting optimum3 plot
xlabel('No Of Iterations')  % x level redinedf for subplot
ylabel('max Function Value')% y label redifined for 2nd subplot
legend('data variation')

# Output of this Code:-

2. Case 1. Statistical analysis using unbounded input:-

3. Statistical analysis using Bounded input:-

It is clearly seen from the above plot that after providing the boundary limits, variation in the optimum value of the function has reduced.

4. Case 3:- Bounded input but increased population size:-

# Work space variables:-

# Conclusion:-

  • Here we get the idea behind that, how the “ga ()” commands works with different inputs and how to obtain a same value for a function even if “ga” is run several times.
  • Global Maxima is found for the stalagmite function with the help of "ga" command.
  • Genetic Algorithm is one of the most used method for obtained optimized value.
  • Genetic Algorithm is mostly used to find the minimum value of a function , for example to find minimum drag force that will be created by the Aerofoil
  • Similar approach as above code can be used to find maximum value using “ga” command

# Refrences:-

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.