Challenge

MATLAB code to optimize the stalagmite function and find the global maxima of the function

Genetic Algorithm

OBJECTIVE:

We have to

  1. Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
  2. Clearly explain the concept of genetic algorithm and also explain the syntax for ga in MATLAB

THEORY:

A genetic algorithm is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution. This algorithm reflects the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.

Notion of Natural Selection

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.

This notion can be applied for a search problem. We consider a set of solutions for a problem and select the set of best ones out of them.

Five phases are considered in a genetic algorithm.

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

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.

An individual is characterized by a set of parameters (variables) known as Genes. Genes are joined into a string to form a Chromosome (solution).

In a genetic algorithm, the set of genes of an individual is represented using a string, in terms of an alphabet. Usually, binary values are used (string of 1s and 0s). We say that we encode the genes in a chromosome.

Population, Chromosomes and Genes

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.

Selection

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

Two pairs of individuals (parents) are selected based on their fitness scores. Individuals with high fitness have more chance to be selected for reproduction.

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.

For example, consider the crossover point to be 3 as shown below.

Crossover point

Offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.

Exchanging genes among parents

The new offspring are added to the population.

New offspring

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.

Mutation: Before and After

Mutation occurs to maintain diversity within the population and prevent premature convergence.

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 OF GA:

x = ga(fun,nvars)

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

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

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

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

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

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

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

x = ga(problem)

[x,fval] = ga(___)

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

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

EXPLANATION:

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.

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

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

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.)

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.)

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.

x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon) or x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options) requires that the variables listed in IntCon take integer values.

x = ga(problem) finds the minimum for problem, a structure described in problem.

[x,fval] = ga(___), for any previous input arguments, also returns fval, the value of the fitness function at x.

[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.

[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.

MATLAB CODE:

1.Function Code:

function [f] =stagalmite(input_vector)

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

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

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

[f]=-((f1_x)*(f2_x)*(f1_y)*(f2_y));

end


2.Main Code:

%MATLAB  code to optimize the stalagmite function and find the global
%maxima of the function
clear all
close all
clc

%Defining the Search area 1D Array

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

%Creating 2D array

[xx,yy]=meshgrid(x,y);

%Evaluating 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)=stagalmite(input_vector);
    end
end

%Sttudy1 statastical behaviour with unbound input values
tic
for i=1:num_cases
    [results,fopt(i)]=ga(@stagalmite,2);
    xopt(i)=results(1);
    yopt(i)=results(2);
end
study1_time=toc


%Plotting 1

figure(1)           
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('Function Maximum')

%Study2 Statistical behaviour with  upper and lower bounded input values

tic
for i=1:num_cases
    [results,fopt(i)]=ga(@stagalmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(i)=results(1);
    yopt(i)=results(2);
end
study2_time=toc

%Plotting 2

figure(2)           
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('Function Maximum')

%Study3 Statistical behaviour with  upper and lower bounded input values
%and by increasing iterations


options=optimoptions('ga')
options=optimoptions(options,'populationsize',250)

tic
for i=1:num_cases
    [results,fopt(i)]=ga(@stagalmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
    xopt(i)=results(1);
    yopt(i)=results(2);
end
study3_time=toc

%Plotting 3

figure(3)           
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('Function Maximum')


EXPLANATION OF CODE:

1.First as usual we have used

Clear all command used to clear text from the Command Window before running a command.

Close all command used to close all the plots window.

clc command is used to Clear Command Window

2.In Function code we are coding for the given equation

Here in this stalagmite function we breakdown the equation into 4 and we have given the terms

And also, in this challenge we have find the global maxima so usually ga iterates for minimum value so we have used (-ve) , Minimize means It will produce least value of plot so if you use -ve means it will replicate the plot so we will get the max value

3.Then we have created the space area of 1D array using Linspace command and given the number of iterations as num_cases and using meshgrid command we have create the 2D array

4.Next step we have evaluated the stalagmite function using for loop where we have stored the values into input_vector array from 2D array. Then we have called the stalagmite function

5.Now we are going to run 3 studies

In first study statistical behaviour with unbound input values and in second study Statistical behaviour with upper and lower bounded input values and finally we run for Statistical behaviour with upper and lower bounded input values

and by increasing iterations

If we consider the study1 here to calculate the time we have used tic toc command. In for loop we iterate to 50 and then we call the ga function using the syntax 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

And we store the results1 and results2 in the array called xopt and yopt

If we consider the second study we starts with tic toc command to get the time and then the syntax used is 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.) And we store the results in the xopt and yopt array

If we consider the study 3 we starts with tic toc command to get the time and in this study using optimoptions command where syntx used is options = optimoptions(SolverName) and options = optimoptions(SolverName) returns a set of default options for the SolverName solver and again we use another syntax options = optimoptions(oldoptions,Name,Value) it will returns a copy of oldoptions with the named parameters altered with the specified values.

6.If we consider the Plotting sections we will create the figure window and then we create the subplot in the figure window where subplot(m , n , p ) divides the current figure into an m -by- n grid and creates axes in the position specified by p .An using surfc command to create the surface using the inputs x,y,-f and using shading interp varies the color in each line segment and face by interpolating the colormap index or true color value across the line or face. After that we create a plot with 3 inputs where plot3( X , Y , Z ) plots coordinates in 3-D space. To plot a set of coordinates connected by line segments, specify X , Y , and Z as vectors of the same length. To plot multiple sets of coordinates on the same set of axes, specify at least one of X , Y , or Z as a matrix and the others as vectors.

We plot the function value that we obtained and using labelling command we label them

RESULTS AND OBSERVATION:

STUDY1:

STUDY2:

STUDY3:

RESULTS:

Here in first study the function value varies between 0-1 and that is not accurate so we have given the lower and upper bound it will create the boundary to search but still the value of function is not satisfied and our satisfied results got by increasing the iterations

ERROR:

In line 80 i have forgot to add the i in fopt,After adding the 'i' it works properly,Beacues we adding each value of 'i' in fopt

REFERENCES:

  1. https://in.mathworks.com/help/gads/ga.html#d122e38381
  2. https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3
  3. https://en.wikipedia.org/wiki/Genetic_algorithm
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.