Challenge

 Genetic Algorithm to calculate the Global Maxima of Stalagmite Function using MATLAB

TITLE: Genetic Algorithm to calculate the Global Maxima of Stalagmite Function using MATLAB.

AIM: Genetic Algorithm to calculate the Global Maxima of Stalagmite Function using MATLAB. To study about Genetic Algorithm and to calculate the global maxima of stalagmite function using the Genetic
Algorithm in MATLAB.

OBJECTIVE:

> To define the stalagmite function
> To find the optimum valu of the stalagmite function through

1) Statistical behaviour method
2) Statistical behaviour with bounds method
3) Statistical behaviour with bounds and population size method

> Calculate Gobal maxima

GENETIC ALGORITHM

A genetic algorithm is the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.

The process of natural selection starts with the selection of fittest individuals from a population. They produce offspring which inherit the characteristics of the parents and will be added to the next generation. If parents have better fitness, their offspring will be better than parents and have a better chance at surviving. This process keeps on iterating and at the end, a generation with the fittest individuals will be found.

Five phases are considered in a genetic algorithm.

  1. Initial population
  2. Fitness function
  3. Selection
  4. Crossover
  5. Mutation

  1. Initial Population

The process begins with a set of individuals which is called a Population. Each individual is a solution to the problem you want to solve.

  1. Fitness Function

The fitness function determines how fit an individual is (the ability of an individual to compete with other individuals). It gives a fitness score to each individual. The probability that an individual will be selected for reproduction is based on its fitness score.

3. Selection

The idea of selection phase is to select the fittest individuals and let them pass their genes to the next generation.

  1. Crossover

Crossover is the most significant phase in a genetic algorithm. For each pair of parents to be mated, a crossover point is chosen at random from within the genes.

  1. Mutation

In certain new offspring formed, some of their genes can be subjected to a mutation with a low random probability. This implies that some of the bits in the bit string can be flipped.

  1. Termination

The algorithm terminates if the population has converged (does not produce offspring which are significantly different from the previous generation). Then it is said that the genetic algorithm has provided a set of solutions to our problem.

SYNTAX

1) x = ga(fun,nvars):

Finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dimension (number of design variables) of fun.

2) x = ga(fun,nvars,A,b):

Finds a local minimum x to fun, subject to the linear inequalities A*x ≤ b. ga evaluates the matrix product A*x as if x is transposed (A*x').

3) x = ga(fun,nvars,A,b,Aeq,beq):

Finds a local minimum x to fun, subject to the linear equalities Aeq*x = beq and A*x ≤ b. (Set A=[] and b=[] if no linear inequalities exist.) ga evaluates the matrix product Aeq*x as if x is transposed (Aeq*x').

4) x = ga(fun,nvars,A,b,Aeq,beq,lb,ub):

Defines a set of lower and upper bounds on the design variables, x, so that a solution is found in the range lb ≤ x ≤ ub. (Set Aeq=[] and beq=[] if no linear equalities exist.)

5) x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon):

Subjects the minimization to the constraints defined in nonlcon. The function nonlcon accepts x and returns vectors C and Ceq, representing the nonlinear inequalities and equalities respectively. ga minimizes the fun such that C(x) ≤ 0 and Ceq(x) = 0. (Set lb=[] and ub=[] if no bounds exist.)

6) x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options):

Minimizes with the default optimization parameters replaced by values in options. (Set nonlcon=[] if no nonlinear constraints exist.) Create options using optimoptions.

7) x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon):

Requires that the variables listed in IntCon take integer values.

8) x = ga(problem):

Finds the minimum for problem, where problem is a structure.

9) [x,fval] = ga(___):

For any previous input arguments, also returns fval, the value of the fitness function at x.

10) [x,fval,exitflag,output] = ga(___):

Also returns exitflag, an integer identifying the reason the algorithm terminated, and output, a structure that contains output from each generation and other information about the performance of the algorithm.

11) [x,fval,exitflag,output,population,scores] = ga(___):

Also returns a matrix population, whose rows are the final population, and a vector scores, the scores of the final population.

HOW THE GENETIC ALGORITHM WORKS

Outline of the Algorithm

The following outline summarizes how the genetic algorithm works:

  1. The algorithm begins by creating a random initial population.
  2. The algorithm then creates a sequence of new populations. At each step, the algorithm uses the individuals in the current generation to create the next population. To create the new population, the algorithm performs the following steps:
    1. Scores each member of the current population by computing its fitness value. These values are called the raw fitness scores.
    2. Scales the raw fitness scores to convert them into a more usable range of values. These scaled values are called expectation values.
    3. Selects members, called parents, based on their expectation.
    4. Some of the individuals in the current population that have lower fitness are chosen as elite. These elite individuals are passed to the next population.
    5. Produces children from the parents. Children are produced either by making random changes to a single parent—mutation—or by combining the vector entries of a pair of parents—crossover.
    6. Replaces the current population with the children to form the next generation.

3. The algorithm stops when one of the stopping criteria is met.

Stalagmite Function:


> It is a mathematical model that helps to generate local minima and maxima.
> It is a three-dimensional function and the way the function is designed is that it has a lot of local maxima or minima and one global maxima or minima.
> The name stalagmite is actually a type of rock formation that rises from the floor of a cave due to the accumulation of material deposited on the floor from ceiling drippings.

BODY OF CONTENT

Program for Stalagmite function

%Program to Define the Stalagmite Function
function [f] = stalagmite_func(input_vector)

%Inputs
x = input_vector(1);
y = input_vector(2);

%Solution of the function f(x,y) = (f_1,x)*(f_2,x)*(f_1,y)*(f_1,y)
%                                   -----   -----   -----   -----
%                                   term1   term2   term3   term4
%Calculation of all terms
term1 = (sin((5.1*pi*x )+ 0.5))^6;
term2 = (sin((5.1*pi*y) + 0.5))^6;
term3 = exp(-4*log(2)*((x-0.0667)^2)/0.64);
term4 = exp(-4*log(2)*((y-0.0667)^2)/0.64);

f = -(term1*term2*term3*term4);

end

Program for Genetic Algorithm

%Program to calculate Global maxima of a Stalagmite function

clear all
close all
clc

% Defining the search space OR range
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
%Total no. of Iterations
n = 50;

%Calculating Stalagmite function and equating to vector f

[xx,yy]= meshgrid(x,y);
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_func(input_vector);
    end
end

%Study 1: statistical behaviour
tic
for i=1:n
    [inputs,fopt(i)]=ga(@stalagmite,2);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end

study_1_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')

%Study 2: statistical behaviour with bounds

for k = 1:n
[inputs2 , fopt2(k)] = ga(@stalagmite_func, 2,[],[],[],[],[0;0],[1;1]);
xopt2(k) = inputs2(1);
yopt2(k) = inputs2(2);
end

figure(3)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp

plot3(xopt2,yopt2,-fopt2,'marker','o','markerfacecolor','r')
xlabel('X values')
ylabel('Y values')
title('Statistical Behaviour - with upper and lower bound')
figure(4)
subplot(2,1,2)
plot(-fopt2)
xlabel('Iterations')
ylabel('fopt')
title('Statistical Behaviour - with upper and lower bound')

%Study 3 increasing GA iterations

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

for i=1:num_cases
[inputs, fopt(i)]= ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],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('Bounded inputs with modified population size')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function maximum')

Explaination:

1) Start the program with 'clear all','close all', and 'clc' commands

2) First, we have to write a program for the Stalagmite function. Solving the Genetic algorithm for stalagmite function gives us a minimum value of the function. To find the maximum value of the function, we need to change the sign of function, so that it will give value for the reverse case of minima, i.e. maxima.

3) Now we need to define the search space for finding the values of x & y in the stalagmite function. The search space is chosen to be between 0 to 0.6 with 150 intervals. For this we have used 'linspace()'. Genetic Algorithm can take no. of iterations each time we run the code giving different values each time. To save the time of calculations we have restricted our script to run for 50 iterations only. It doesn't mean function will give maximum value in 50 iterations. We will consider whatever maximum value that came within those 50 iterations. We have restricted our area of search. These no of iterations is given by 'n=50'.

4) As 'linspace()' creates the series of nos, x & y will be the column vector. As input to the stalagmite function, we need to convert the column vector to a row vector. The first step of this conversion is to create the 'meshgrid(x,y)'. Next, we use 'for' loop for conversion.

5) The next step is to obtain the results for 3 cases of the genetic algorithm in Matlab. In the first case, maximum value of the function is found out with no restrictions, no bounds, and no limits. Genetic algorithm is free to choose the population then reproduce and mutate.

6) To get the same value each time we run the program, we need to restrict the program within specific bounds namely upper bound and lower bound. The whole procedure for programming this case the same as that of the previous one, exception being for GA.

7) Even the results from the bounded cases are not the same every time the program terminates. Hence we now need to increase GA iterations. We can raise it to any value, we have chosen it as 300. In this case, syntax for GA is different than the previous case. GA has to give this population size via an option.

8) Results for this case will be just one value of function which does not deviate with no of iterations.

RESULT's:

Study 1: Statistical Behaviour

Study 2: Statistical Behaviour with upper and lower bound

Study 3: Statistical Behaviour with increasing GA iterations

> After providing upper-lower bounds and options, it seems that value of co-ordinates x,y coverges to only one value for each iteration. Values of x = 0.0668 & y = 0.0668.
> The Above graph shows that variations in values of a function are very low than that of other cases. The value of fopt comes out to be nearly 1.

CHECKING by Optimization tool from MATLAB:

References:

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

2) https://www.mathworks.com/discovery/genetic-algorithm.html

3) https://in.mathworks.com/help/gads/examples/genetic-algorithm-options.html

4) https://in.mathworks.com/help/gads/ga.html#mw_f69991d0-5b23-4023-8c8e-e2890f2474d5

5) https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3

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.