Challenge

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:

The genetic algorithm(GA) is a method for solving both constrained and unconstrained optimization problems that is based on natural selection, the process that drives biological evolution. The genetic algorithm repeatedly modifies a population of individual solutions. At each step, the genetic algorithm selects individuals at random from the current population to be parents and uses them to produce the children for the next generation. Over successive generations, the population "evolves" toward an optimal solution. You can apply the genetic algorithm to solve a variety of optimization problems that are not well suited for standard optimization algorithms, including problems in which the objective function is discontinuous, nondifferentiable, stochastic, or highly nonlinear. The genetic algorithm can address problems of mixed integer programming, where some components are restricted to be integer-valued.

STALAGMITE FUNCTION :

stalagmite function is an upward-growing mound of minerals deposits that have precipitated from water dripping onto the floors of the caves most stalagmite have rounded or flattenened tips.

A stalagmite function generally refers to the function with which we are generating values over a stalagmite kind of surface for find out the local and global maxima and minima of a particular given function.

For this in matlab we are using a method called 'optimization' it is a programming which does not selecting of a best element with regard to some criterion from some set of population.

optimization is done by systematically choosing input values from within an allowed set and computing the results of the function.

in matlabto perform optimization we use Genetic Algorithm method which is a inbuilding function in matlab to find the global maxima of that given stalagmite function.

Introduction to Genetic Algorithm

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.

Initial population

Fitness function

Selection

Crossover

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.

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.

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 algorithm has provided a set of solutions to our problem.

SYNTAX FOR GENETIC ALGORITHM:
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,Aeq,beq,lb,ub,nonlcon,intcon)
x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon,options)
x = ga(problem)
[x,fval] = ga(_)
[x,fval,exitflag,output] = ga(_)
[x,fval,exitflag,output,population,scores] = ga(_)

DISCRIPTION FOR GENETIC ALGORITHM 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.

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,Aeq,beq,lb,ub,nonlcon,intcon) or x = ga(fun,nvars,A,b,Aeq,beq,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.

PROGRAM:

%global_maxima_function
clear all
close all
clc

x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
num_space=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(input_vector);
end
end
%study 1-unbounded
tic
for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2)
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_1=toc
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')
%study 2- bounded
tic
for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6])
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_2=toc
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')
%study3- increased initial population
tic
options=optimoptions('ga')
options=optimoptions(options,'populationsize',250)
for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options)
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_3=toc
figure(3)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')

%surfc(xx,yy,f)

shading interp
[x,fval]=ga(@stalagmite,2)

STALAGMITE FUNCTION CODE

function A =stalagmite(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2)*((x-0.0667).^2))/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2)*((y-0.0667).^2))/0.64);
A=-(f1*f2*f3*f4);
end

EXPLINATION:

PROGRAM:

%global_maxima_function
clear all
close all
clc

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

first we initialise the values of x and y taking 150

values between the interval 0 to 0.6

we consider no of itrations 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(input_vector);

scince we need to plot a 3D surface plot we take a 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 functionfile for stalagmite function here we take the output as -f since ga only minimises a given function. so if -f is considerded it automatically gives us the maxima.

function A =stalagmite(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2)*((x-0.0667).^2))/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2)*((y-0.0667).^2))/0.64);
A=-(f1*f2*f3*f4);
end

now let us make our first study

we take no of itrations=num_spaces and we use the genetic algorithm function to calculate the maxima of the function. we store the out puts into results which contains maximas and fopt which contains the maxima is obtained

Hence the ga is initiated with random population

tic
for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2)
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_1=toc
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')

now we store the results into xopt,yopt. now we need to plot the surfaces x,y,-f to get the 3D plot.

we use the plot 3 command to make a plot of xopt,yopt,-fopt to plot optimum maximas

Also iet us plot the fopt function so that we can visualize the optimum values at each iteration.

to get the time taken to complete cycle we used the tic toc command to record the time

if the study is executed the output is displayed as

Here we can see the optimal values went outside the values of x and y results in falling away from stalagmite surface.

so we failed to reach the global maxima in this case study time

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

for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6])
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_2=toc
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')

now we store the results into xopt,yopt. now we need to plot the surfaces x,y,-f to get the 3D plot.

we use the plot 3 command to make a plot of xopt,yopt,-fopt to plot optimum maximas

Also iet us plot the fopt function so that we can visualize the optimum values at each iteration.

to get the time taken to complete cycle we used the tic toc command to record the time

if the study is executed the output is displayed as

Though the optimum values are with in the limits it could not gives us the exact maxima values.

The time study is more than above time study.

Now iet us make third study with initial population and bounded values

in this case let us increase our initial population which is default as 50 to 250

%study3- increased initial population
tic
options=optimoptions('ga')
options=optimoptions(options,'populationsize',250)
for i=1:num_space
[result,fopt(i)]=ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options)
xopt(i)=result(1)
yopt(i)=result(2)
end
study_time_3=toc
figure(3)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'marker','0')
subplot(2,1,2)
plot(-fopt)
xlabel('interaction')
ylabel('function maximum')

here in this case is set to the initial population we need to use the command called 'optimaloptions' and get our value of population size to 250

now we store the results into xopt,yopt. now we need to plot the surfaces x,y,-f to get the 3D plot.

we use the plot 3 command to make a plot of xopt,yopt,-fopt to plot optimum maximas

Also iet us plot the fopt function so that we can visualize the optimum values at each iteration.

to get the time taken to complete cycle we used the tic toc command to record the time

if the study is executed the output is displayed as

iteration

though the time of executing is more in this case we are sucessful to find out the correct maxima of the stalagmite function

so by increasing the initial population size for the ga we can increase the accuracy of the algorithm

the study time is more then above two studies

OUTPUT:

Iterations

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.