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

Objective

  • Clearly explain the concept of genetic algorithm
  • Explain syntax for ga
  • Plot graphs for all 3 studies for F Maximum vs. no of iterations

Introduction

Optimization Optimization is the act of obtaining the best result under a given circumstances. Optimization is the mathematical discipline which is concerned with finding the maxima and minima of functions

Stalagmite function 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. Stalagmite showing function maximum and minimum (Global & Local)

Genetic algorithm 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

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.

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

The new offspring are added to the population

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.

difference between Genetic Algorithm and Traditional Algorithm

Genetic Algorithm

Traditional Algorithm

Genetics and natural selection to solve optimization problem

Step by step procedure to solve a given problem

More Advanced

Not as advanced

Used in field such as Machine learning and artificial intelligent

Used to fields such as programming, mathamatics

Probabilistic Rules

Fully deterministic rules

Search solution on a population of point

Search solution on single point

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(___)
  • ga(fun,nvars) finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dx = 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.imension (number of design variables) of fun.
  • 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 (code) to solve genetic algoritham

  • code for Stalagmite function
function [f]=func(input_vector)

a1=(sin(5.1*pi*input_vector(1)+0.5))^6;
a2=(sin(5.1*pi*input_vector(2)+0.5))^6;
a3=exp(-4*log(2)*((input_vector(1)-0.0667)^2)/(0.64));
a4=exp(-4*log(2)*((input_vector(2)-0.0667)^2)/(0.64));
f=-(a1*a2*a3*a4);
end
  • code for Genetic algoritham

close all
clear all
clc

 %input
 x=linspace(0,0.6,150)
 y=linspace(0,0.6,150)   

 num_cases=60

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

 %fuction calling
 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)=func(input_vector);
     end
 end

 %case1 unbounded inputs
tic
for i=1:num_cases
    [inputs,fopt(i)]=ga(@func,2);
    xopt(i)=inputs(1);
    yopt(i)=inputs(2);
end
 time1=toc
 % case1
 figure(1)
 subplot(2,1,1)
 hold on 
 surfc(x,y,-f)
 shading interp
 xlabel('iterations in x ')
 ylabel('function maxima')
 zlabel('iterations in z')
 plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
 legend('minima point','maxima point')
 title('unbounded inputs')
 subplot(2,1,2)
 plot(-fopt)
 xlabel('iterations')
 ylabel('function maxima')

 %case study 2 bounded inputs
 tic
 for i=1:num_cases
     [inputs,fopt(i)]=ga(@func,2,[],[],[],[],[0,0],[0.5,0.5]);
     xopt(i)=inputs(1);
     yopt(i)=inputs(2);
 end
 time2=toc
 %bounded inputs 
 figure(2)
 subplot(2,1,1)
 hold on
 surfc(x,y,-f)
 shading interp
 xlabel('iterations in x ')
 ylabel('function maxima')
 zlabel('iterations in z')
 plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
 legend('minima point','maxima point')
 title('bounded inputs')
 subplot(2,1,2) 
 plot(-fopt)
 xlabel('iterations')
 ylabel('function maxima')

 %case study 3 optimisation 
options=optimoptions('ga');
options=optimoptions(options,'PopulationSize',200);
tic
for i=1:num_cases
 [inputs,fopt(i)]=ga(@func,2,[],[],[],[],[0;0],[0.5;0.5],[],[],options);
     xopt(i)=inputs(1);
     yopt(i)=inputs(2);
end
time3=toc
%optimisation
figure(3)
subplot(2,1,1)
 hold on
 surfc(x,y,-f)
 shading interp
 xlabel('iterations in x ')
 ylabel('function maxima')
 zlabel('iterations in z')
 plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r')
 legend('minima point','maxima point')
 title('optimisation')
 subplot(2,1,2)
 plot(-fopt)
 xlabel('iterations')
 ylabel('function maxima')



Step wise explanation of code

1.Stalagmite function

as we discusson the theory of the stalagmite function to solved the equvation we create new strip in matlab and creating the function ''func'' store in array [f] then sliting the the Stalagmite function in to a1,a2,a3,a4 and assign to the f puting -ve because ga calculating mimima only

function [f]=func(input_vector)
a1=(sin(5.1*pi*input_vector(1)+0.5))^6;
a2=(sin(5.1*pi*input_vector(2)+0.5))^6;
a3=exp(-4*log(2)*((input_vector(1)-0.0667)^2)/(0.64));
a4=exp(-4*log(2)*((input_vector(2)-0.0667)^2)/(0.64));
f=-(a1*a2*a3*a4);
end

2.Genetic algoritham

to close privous windows close all
clear privious data clear all
to clear coommand window clc
%input
x=linspace(0,0.6,150)
y=linspace(0,0.6,150)
to create an evenly spaced sequence in a specific interval
num_cases=60 assign number space as 60
[xx yy]= meshgrid(x,y); transforms the domin specifified by vector x and y into arrays
as we assign the 60 cases to solved function we use for loop
to find the maxima of the function we use the inbuild functin of matlab call as "ga"
case1
unbounded inputs
[inputs,fopt(i)]=ga(@func,2);
ga(fun,nvars) finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dx = 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') to calculate for 50 cases we use for loop for that
tic time1=toc use in starting of for loop to ending of for loop to display time to sovled equation
to show result into graphical form we use the following code
subplot(2,1,1) place the multiple fig within the same window
hold on to show all result on same fig
surfc(x,y,-f) to creating 3 d surface plot
shading interp to remove the grid line from surface and show accurate point
xlabel('iterations in x ')
ylabel('function maxima')
zlabel('iterations in z') assign name to the asxis
plot3(xopt,yopt,-fopt,'marker','o','MarkerSize',5,'MarkerFaceColor','r') to showing the maximum point on the fig
legend('minima point','maxima point') assign the name of the points
title('unbounded inputs') to giving tittle name
subplot(2,1,2) place the multiple fig within the same window
plot(-fopt) to show the result of the maxima
xlabel('iterations')
ylabel('function maxima') assign name to the axis
in case1 we get all randan maxima not getting acurate result but we know the boundary condiatin then we use those boundary to find maxima
case2
bounded inputs
[inputs,fopt(i)]=ga(@func,2,[],[],[],[],[0,0],[0.5,0.5]);
  • 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.) using this ga syntax we gate 4 maxima ponit then again using following ga syntax to find one maxima point
case3
optimisation
[inputs,fopt(i)]=ga(@func,2,[],[],[],[],[0;0],[0.5;0.5],[],[],options);
  • 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. using this ga syntax we get the final maxima point

RESULT

case1
unbounded inputs
time take to run program =4.9902 sec
case2
bounded inputs
time take to run program =5.2508
case3
optimisation
time take to run program =13.6884
ERROR
in the for loop by mistakly i write input insted of inputs becase of that program not running to overcome this error checking the program
and to sovled some quaries taking one on one section
for i=1:num_cases
[inputs,fopt(i)]=ga(@func,2);
xopt(i)=input(1);
yopt(i)=input(2);
end
Refrances :
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.