Week 4.1 - Genetic Algorithm
Aim: Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
Theory: Genetic Algorithm (GA) is a search-based optimization technique based on the principles of Genetics and Natural Selection. It is frequently used to find optimal or near optimal-solutions to difficult problems which otherwise would take a lifetime to solve. It is frequently used to solve optimization problems in research and machine learning.
Introduction to Optimization
Optimization is the process of making something better. In any process we have a set of inputs and set of outputs as shown in the following figure.

Optimization refers to finding the values of inputs in such a way that we get the "best" output values. The defenition of "best" varies from problem to problem, but in mathematical terms, it refers to maximizing or minimizing one or more objective functions, by varying the input parametres.
The set of all possible solutions or values which the input can take make up the search space. In this search space, lies a point or a set of points which gives the optimal solution. The aim of optimization is to find that point or set of points in the search space.
Stalagmite Function
- A stalagmite is an upward-growing mound of mineral deposits that have precipitated from water dripping onto the floor of a cave. Most stalagmites have rounded or flattened tips.
- A stalagmite function generally refers to the function with which we are generating values over a stalagmite kind of surface for finding out the local and global maxima and minima of that particular given function.
- Optimization is done by systematically choosing input values from within an allowed set and computing the results of the function.
- In matlab to perform optimization we use 'Genetic Algorithm 'method which is a inbuild function in matlab to find the global maxima of that given stalagmite function.
What are Genetic Algorithms
Nature has always been a great source of inspiration to all mankind. Genetic Algorithms (GAS) are search based algorithms based on the concepts of natural selection and genetics. GAs are a subset of a much larger branch of computation known as Evolutionary Computation.
GAS were developed by John Holland and his students and colleagues at the University of Michigan, most notably David E. Goldberg and has since been tried on various optimization problems with a high degree of success
In GAS, we have a pool or a population of possible solutions to the given problem. These solutions then undergo recombination and mutation (like in natural genetics), producing new children, and the process is repeated aver various generations. Each individual (or candidate solution) is assigned a fitriess value (based on its objective function value) and the fitter individuals are given a higher chance to mate and yield more "fitter individuals. This is In line with the Darwinian Thoory of "Survival of the Fittest.
In this way we keep "evolving" better individuals or solutions over generations, till we reach a stopping criterion.
Genetic Algorithms are sufficiently randomized in nature, but they perform much better than rondom local search (in which we just try various random solutions, keeping track of the best so far), as they explait historical information as well.
Process 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.
- Initial Population
- Fitness Function
- Selection
- Cross Over
- 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. 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 Is and Os). We say that we encode the genes in a chromosome.
- Fitness Function-Fitness Function (also known as the Evaluation Function) evaluates how close a given solution is to the optimum solution of the desired problem. It determines how fit a solution is.
- why we use fitness functions
In genetic algorithms, each solution is generally represented as a string of binary numbers, known as a chromosome. We have to test these solutions and come up with the best set of solutions to solve a given problem. Each solution, therefore, needs to be awarded a fitness score, to indicate how close it came to meeting the overall specification of the desired solution. This score is generated by applying the fitness function to the test, or results obtained from the tested station. Genetic Algorithms are sufficiently randomized in nature, but they perform much better than rondom local search (in which we just try various random solutions, keeping track of the best so far), as they explait historical information as well.
3.Selection
The selectionj is based on the fitness score. 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.
4.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. Offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.
- 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 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 algorithmn has provided a set of solutions to our problem. The population has a fixed size. As new generations are formed, individuals with least fitness die, providing space for new offspring. The sequence of phases is repeated to produce individuals in each new generation which are better than the previous generation. Ga as function of matlab.
Syntax for genetic algorithm
we can give the inputs by any one of the following ways
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) ga(fun,nvars,A,b,[],[], x = ga(fun, nvars, A, b, [], [], 1b, ub, nonlcon, IntCon)
x = ga(fun, nvars, A, b, [], [], 1b, ub, nonlcon, IntCon, options) ga(fun,nvars,A,b,[],[],
x = ga(problem) X
[x,fval] = ga(__)
[x, fval, exitflag, output] = ga(___)
[x.fval.exitflag.output.population, scores] = ga( )
Description Of Input Variables
These are the various input syntaxes that can be given
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, Aeq, beq) finds a local minimum to fun, subject to the linear inequalities A*x ≤ b. ga be evaluates the matrix product A*x as if x is transposed (A*x').
x=ga (fun, nvars, A, b, Aeq, bea) 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, so that a solution is found in the range 1b ≤ 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 1b=[] 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.
When there are integer constraints, ga does not accept linear or nonlinear equality constraints, only inequality constraints.
x = ga(problem) finds the minimum X for problem, where problem is a structure.
Output from the functions
[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, scores of the final population. the
Program
close all
clear all
clc
%input
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
num_spaces=50;
% forming 2d array
[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_function(input_vector);
end
end
%study 1-unbounded
tic
for i=1:num_spaces
[results,fopt(i)]=ga(@stalagmite_function,2);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time1=toc
figure(1)
subplot(2,1,1)
surfc(xx,yy,-f)
shading interp
hold on
colorbar
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study 2-bounded
tic
for j=1:num_spaces
[results,fopt(j)]=ga(@stalagmite_function,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(j)=results(1);
yopt(j)=results(2);
end
study_time2=toc
figure(2)
subplot(2,1,1)
surfc(xx,yy,-f)
colorbar
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
%study3-increased initial population
tic
% options=optimoptions('ga');
options=optimoptions('ga','populationsize',250);
for k=1:num_spaces
[results,fopt(k)]=ga(@stalagmite_function,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(k)=results(1);
yopt(k)=results(2);
end
study_time3=toc
figure(3)
subplot(2,1,1)
colorbar
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
Stalagmite Function Code
function [A]=stalagmite_function(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*input_vector(1)+0.5)).^6;
f2=exp((-4*log(2))*(input_vector(1)-0.0667).^2/0.64);
f3=(sin(5.1*pi*input_vector(2)+0.5)).^6;
f4=exp((-4*log(2))*(input_vector(2)-0.0667).^2/0.64);
[A]=-(f1*f2*f3*f4);
end
Program Explanation
Program Explanation
close all
clear all
clc
%input
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
num_spaces=50;
First we initialise the values of x and y taking 150 values between the interval 0 and 0.6.
We consider no of interations num_spaces=50
% forming 2d array
[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_function(input_vector);
Since we need to plot a 3D surface plot we take the 2d array of x and y using meshgrid command and store them in input vector array,so that it can be used as an argument to call the function stalagmite.
we create another fuction file for the stalagmite function. here we take the ouput as -f since ga only minimises a given function.so if -f is considered it automatically gives us the maxima.
function [A]=stalagmite_function(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*input_vector(1)+0.5)).^6;
f2=exp((-4*log(2))*(input_vector(1)-0.0667).^2/0.64);
f3=(sin(5.1*pi*input_vector(2)+0.5)).^6;
f4=exp((-4*log(2))*(input_vector(2)-0.0667).^2/0.64);
[A]=-(f1*f2*f3*f4);
end
now let us make our first study we take no of iterations= num_spaces and we use the genetic algorithm function to caluclate the maxima of the function, we store the outputs into results which contain maximas and fopt which contain the value at which the maxima is obtained.Here the ga is initiated with random population.
%study1-increased initial population
tic
for i=1:num_spaces
[results,fopt(i)]=ga(@stalagmite_function,2);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time1=toc
figure(1)
subplot(2,1,1)
surfc(xx,yy,-f)
shading interp
hold on
colorbar
shading interp
plot3(xopt,yopt,-fopt,'marker','o')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maximum')
now we store the results into xopt, yopt.now we need to plot the surface of x,y,-f to get the 3D plot. We use the plot3 command to make a plot of xoptyopt and -fopt to plot the optimum maximas. Also let us plot the fopt functio so that we can visualise the optimum values at each iteration.
To get the time taken to complete cycle we used the tic toc commands to record the time.
If the study is executed the output is dispalyed as:

Here we can see the optimal values went outside the values of x and y resulting in falling away from the stalagmite surprise.
So we failed to reach the gloabl maxima in this case
the study time=10.4865
Now let us make our study having bounded values
let us specify the lower and upper bounds of x and y in this case, the ga is initiated with random population only.
%study2-increased initial population
tic
for j=1:num_spaces

Here in this case to set a initial population we need to use command called optimumaptions and get our value of 'populationsize' to 250.
now we store the results into xopt, yopt.now we need to plot the surface of xy-f to get the 3D plot. We use the plot3 command to make a plot of xoptyopt and -fopt to plot the optimum maximas. Also let us plot the fopt functio so that we can visualise the optimum values at each iteration. To get the time taken to complete cycle we used the tic toc commands to record the time. If the study is executed the output is displayed as

though the time of execution is more i this case we are sucessful to find out the correct maxima for the stalagmite function. So by increasing the initrial population size of the ga we can increase the accuracy of the algorithm.
The study time = 21.8301s which is more than above two studies.
Output
All the output figures are as attached below.
All the explanations for the graphs are explained individually in the program explanation section.