Genetic Algorithm
Objective: 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 in machine learning.
Introduction to Optimization
Optimization is the process of making something better. In any process, we have a set of inputs and a 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 definition 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 parameters.
The set of all possible solutions or values which the inputs 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.
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 over various generations. Each individual (or candidate solution) is assigned a fitness 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 Theory 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 random local search (in which we just try various random solutions, keeping track of the best so far), as they exploit historical information as well.
Syntax for Genectic Algorithm:
Description
finds a local unconstrained minimum, x = ga(fun,nvars)x, to the objective function, fun. nvars is the dimension (number of design variables) of fun.
finds a local minimum x = ga(fun,nvars,A,b,Aeq,beq)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').
defines a set of lower and upper bounds on the design variables, x = ga(fun,nvars,A,b,Aeq,beq,lb,ub)x, so that a solution is found in the range lb ≤ x ≤ ub. (Set Aeq=[] and beq=[] if no linear equalities exist.)
subjects the minimization to the constraints defined in x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)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.)
minimizes with the default optimization parameters replaced by values in x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)options. (Set nonlcon=[] if no nonlinear constraints exist.) Create options using optimoptions.
or x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon) requires that the variables listed in x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)IntCon take integer values.
[ also returns a matrix x,fval,exitflag,output,population,scores] = ga(___)population, whose rows are the final population, and a vector scores, the scores of the final population.
Program Code:
clear all
close all
clc
%Defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_spaces=50;
%Creating a 2Dimensional mesh
[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)=stalagmite_func(input_vector);
end
end
%Study1-Statistical behavior-unbounded
tic
for i= 1:num_spaces
[results,fopt(i)]= ga(@stalagmite_func,2);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time1=toc;
figure(1)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('unbounded input')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maxima')
tic
%Study2-Statistical behavior-with upper and lower bounds
for i = 1:num_spaces
[results,fopt(i)]= ga(@stalagmite_func,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time2=toc;
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('bounded input')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maxima')
%Study3 increasing GA iterations
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',150);
tic
for i = 1:num_spaces
[results,fopt(i)]= ga(@stalagmite_func,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(i)=results(1);
yopt(i)=results(2);
end
study_time3=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 input with modified population size')
subplot(2,1,2)
plot(-fopt)
xlabel('iteration')
ylabel('function maxima')
Stalagmite Function code:
function [f]=stalagmite_func(input_vector)
x=input_vector(1);
y=input_vector(2);
term1=(sin(5.1*pi *x +0.5)).^6;
term2=(sin(5.1*pi *y +0.5)).^6;
term3=exp((-4*0.6931).*(x-0.0667)^2/(0.64));
term4=exp((-4*0.6931).*(y-0.0667)^2/(0.64));
f= -(term1.*term2.*term3.*term4);
end
Program Explanation:
- Firstly a random array of x & y values were created and the corresponding 2D array was obtained using meshgrid function.
- A loop was used to assign values from this array into an array named input_vector,its also the input to the stalagmite function.
- A seperate Stalagmite function is written.Minus(-) sign is given to the output of stalagmite function so that after the ga process,it will give global maxima.(As ga is inbuilt command normally it process global minima).
- Tic-toc commands were used to get the running time of each case.
- In Study_1 the bounds were not defined and the plots were plotted.Here we see that the optimal values went outside the values of x & y resulting in falling away from stalagmite surface.So we failed to reached global maxima in this study.(Study_time1:6.1446)
- In Study_2 bounds with upper and lower bounds. Here though the optimin values were within the limits but it could not give us exact maxima value.(Study_time2:6.776)
- In Study_3 bounded inputs with modified population size. Here though the time of execution is more but we are successful to find out correct maxima for stalagmite function.(Study_time3:16.7339)
Stopping Criteria:
Generations- The algorithm stops when the number of generations reaches the value of generations.
Time limit- The algorithm stops after running for an amount of time in seconds equal to time limit.
Fitness limit- The algorithm stops when the value of the fitness function for the best point in the current population is less than or equal to fitness limit.
Error's while Programming:
1. Many typo errors were encountered.
2. The plots obtained were not proper because 'ga' function is used to find minima but we have to find maxima so we have to introduce negative sign in function code in function definition line.
Outputs:
Study_1:

Study_2:

Study_3:

Reference's:
2.https://www.tutorialspoint.com/genetic_algorithms/genetic_algorithms_introduction.htm
3.https://in.mathworks.com/help/gads/ga.html#d122e38546