Challenge

Week 5 - Genetic Algorithm

AIM : To optimise the stalagmite function and find the global maxima of the function using Matlab Coding and to plot graphs for all 3 studies and for F maximum vs no. of iterations.

OBJECTIVE :

  1. To explain the concept of genetic algorithm and the syntax for ga in MATLAB in your report.
  2. To write a program to optimise the stalagmite function and find the global maxima of the function using Matlab Coding.
  3. To plot graphs for all 3 studies and for F maximum vs no. of iterations.

THEORY :

Genetic Algorithm:

The genetic algorithm 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 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.

This flow chart outlines the main algorithmic steps.

Example:

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 FOR ga IN MATLAB:

Description

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

MATLAB CODE :

%CASE 1: program to to optimise the stalagmite function and find the global maxima of the function.

clear all
close all
clc

%defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases=50;

%creating 2D 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(input_vector);
    end
end


 
tic 
for k= 1:num_cases;
    [inp,fval(k)]=ga(@stalagmite,2);
    x_1(k)= inp(1);
    y_1(k)= inp(2);
end
study1_time=toc

figure(1)
subplot(2,1,1)
hold on
grid on
surfc(xx,yy,-f)
title('stalagmite plot')
xlabel ('X')
ylabel ('Y')
zlabel('Function Vlaues')

shading interp
plot3(x_1,y_1,-fval,'marker','o','markersize',5,'markerfacecolor','g')
title('unbounded inputs')
subplot(2,1,2)
plot(-fval)
xlabel('iterations')
ylabel('function minimum')

%CASE 2: program to study statistical behavior
tic
for s = 1:num_cases
    [input,fval(s)]= ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6]);
    x_2(s)= input(1);
    y_2(s)= input(2);
end
study2_time = toc

figure(3)
subplot(2,1,1)
surfc(xx,yy,-f)
shading interp
hold on
plot3(x_2,y_2,-fval,'marker','o','markersize',5,'markerfacecolor','g')
title('unbounded inputs')
subplot(2,1,2)
plot(-fval)
xlabel('iterations')
ylabel('function minimum')

%CASE 3: program to study increasing ga iterations
options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',500)
tic
for m = 1:num_cases
    [input,fval(m)]= ga(@stalagmite,2,[],[],[],[],[0,0],[0.6,0.6],[],[],options);
    x_3(m)= input(1);
    y_3(m)= input(2);
end
study3_time =toc

figure(4)
subplot(2,1,1)
surfc(xx,yy,-f)
hold on
shading interp


plot3(x_3,y_3,-fval,'marker','o','markersize',5,'markerfacecolor','g')
title('unbounded inputs')
subplot(2,1,2)
plot(-fval)
xlabel('iterations')
ylabel('function minimum')

CODE EXPLANATION:

  1. First, Linspace command is used to define x & y with 150 elements between zero and 0.6 including the bounds. Then num cases is set which will be used as counter for iteration to 50.
  2. then a 2D grid is made using meshgrid command is created from x & y input tobe output to xx & yy.
  3. then for loop is used to solve the genetic algorithm for every element in the 2D mesh grid.
  4. the length of rows & column (which have equal length) are used as counters, then the input vector is declared as ga requires input vector which is each value in the mesh grid.
  5. then output of stalagmite function is stored in matrix,then tic command is used to start a timer, then for loop bounded by the number of iterations is formed, then ga code is entered for unbounded statistical study which have the following format: Tinputs, fopt] ga(fun, nvars) inputs represent the values of parameters x & y for which the function has the least value (fopt).
  6. then figure1 is plotted by the following steps
  7. First subplot command is used to partition the plot window in order to draw more than one plot in the same window, two rows and one column are specified and then the position of
  8. each plot is selected
  9. then x,y,& z axis are labelled
  10. then shading interp is used to smoothen the function plot and to remove the grid lines 19. then plot 3 command is used to plot a point in 3D, here it will plot- fopt because we need
  11. the maximum value of the function not the minimum 20. then the graph title is selected, then fopt value of the function is plotted on the second plot in the second row
  12. then its x & y axis are labelled, then the same study is made but this time it is bounded (has lower & upper limit) which requires the same commands and step excepts the ga command which have the following format:
  13. [input, fopt] ga(fun, nvars, A, b, Aeq, beq, lb, ub) Inputs, fopt, fun & nvars are the same as study-1
  14. the range of the genetic algorithm is bounded by introducing values for lower and upper bounds and hence the values of global maxima and the values of x & y will be within then defined search space in inputs
  15. then increasing population size study was done which is the same as before but it had different ga code of:
  16. [inputs, fopt ga(fun, nvars, A. b. Aeq, beq, lb, ub, nonicon, IntCon, options) = inputs, fopt, fun and nvars, A, b, Aeq, beq lb, ub are the same as study-1 and study-2
  17. the range of the genetic algorithm is bounded as in study-2 but to improove the accuracy,
  18. the commands optimoptions is introduced to increase the Population Size500, then total time is computed
  19. then using fprintf command the results are printed in the command windows, then the study time is printed
  20. then x, y coordinate of the maximum optimum values are printed
  21. then the optimum values of the function (maximum value) is printed which is calculated from the (negative mean) of the all iterations of the output value and the negative sign is used to get the maximum value
  22. then the study time of the whole 3 studies combined is printed.

RESULT :

In figure1, it can be seen that since the inputs are boundless GA algorithm has mapped local maxima points outside our stalagmite function. Also we can not infer a particular value of global maxima from the above graph, and it is hence pointless. The study time is very less as the ga' algorithm is made only to run for 50 iterations.

In figure2 is more clear and optimized compare to the first iterations since here the bounds were defined and we could get only the values within our range. We are now more clear on the range within which our maxima lies.

In figure4, we are getting the optimized value of global maxima with accurate range, since we increased the number of iterations and population size. Since the number of iterations and population size is increased the study time is so high.

CONCLUSION : In conclusion, by using all these cases or studies the most optimised genetic algorithm for population we find out better case to find exact values of population.

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.