Challenge

Genetic Algorithm

Aim: To understand the concept of genetic algorithm, stalagmite function and ways to optimize.

Governing Equations:

Objective:

  1. Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
  2. Clearly expalin the concept of genetic algorithm in your own words and also explain the syntax for ga in MATLAB in your report.
  3. Make sure that your code gives the same output, even if it is made to run several times.
  4. Plot graphs for all 3 studies and for F maximum vs no. of iterations. Title and axes labels are a must, legends could be shown if necessary.

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 slues over a stalagmite kind of surface for finding out the local and global maxima and minima of that particularly given function.

“Optimization” is the method to use this function. It is programming that does a selection of the best element regarding some criterion from some set of population. The 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 the “Genetic Algorithm” method which is an in-build function in MATLAB to find the global maxima of that given stalagmite function.

Concepts of Generic Algorithm:

Genetic Algorithm:

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.

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

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 1s and 0s). We say that we encode the genes in a chromosome.

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

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

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.

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

‘ga’ Syntax and its Description:

Syntax:

“ga” is used to find minimum of function using 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,[],[],lb,ub,nonlcon,IntCon)

x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)

x = ga(problem)

[x,fval] = ga(___)

[x,fval,exitflag,output] = ga(___)

[x,fval,exitflag,output,population,scores] = ga(___)

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,[],[],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.

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.

Input Arguments:

fun — Objective function

nvars — Number of variables

A — Linear inequality constraints

b — Linear inequality constraints

Aeq — Linear equality constraints

beq — Linear equality constraints

lb — Lower bounds

ub — Upper bounds

nonlcon — Nonlinear constraints

options — Optimization options

IntCon — Integer variables

problem — Problem description

Output Arguments:

x — Solution

fval — Objective function value at the solution

exitflag — Reason ga stopped

output — Information about the optimization process

population — Final population

scores — Final scores

MATLAB Code:

Stalagmite Function Code:

function [f]= stalagmite_function(inputs_variable)
f1x=(sin((5.1*pi).*inputs_variable(1)+0.5)).^6;
f1y=(sin((5.1*pi).*inputs_variable(2)+0.5)).^6;
f2x= exp(((-4*log(2)).*(((inputs_variable(1)-0.0667).^2)/0.64)));
f2y= exp(((-4*log(2)).*(((inputs_variable(2)-0.0667).^2)/0.64)));
f1=f1x*f1y*f2x*f2y;
f=-f1;
end

Main Program Code:

clear cll
close all
clc

%Program to optimise the stalagmite function and find global maxima of the function

% Creating 1D array
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
iterations=30;          % Total no. of iterations to run

%Creating 2D array using meshgrid function
[xx yy]=meshgrid(x,y);      % These 2D array were created from above 1D array (from x,y)

% Evaluting the stalagmite function
for i=1:length(xx)
    for j=1:length(yy)
        inputs_variable(1)=xx(i,j);
        inputs_variable(2)=yy(i,j);
        f(i,j)=stalagmite_function(inputs_variable); 
    end
end

%Study-1: Statistical behavior
tic         % tic and toc commands are used to calculate the study time
for i=1:iterations
    [input,f_optimum(i)]=ga(@stalagmite_function,2);
    x_optimum(i)=input(1);      % To store optimum value of x
    y_optimum(i)=input(2);      % To store optimum value of y  
end
study_time_1=toc

figure(1)               % To open new figure window
subplot(2,1,1)          % To combine two or more plot in one figure
surfc(xx,yy,-f)         % To contour plot under surface plot
xlabel('x-values')      % Labelling x-axis
ylabel('y-values')      %labelling y-axis
title('Study-1 (Statistical behavior)') %Labeling title of figure
shading interp              %To set color shading properties
hold on;    
plot3(x_optimum,y_optimum,-f_optimum,'marker','o'); % Plotting the curve from optimum values of x, y, and f
subplot(2,1,2)
plot(-f_optimum);        % To plot f values
xlabel('No. of Iterations')
ylabel('Maximum function value')

%Study-2: Statistical behavior with upper and lower bounds

tic
for i=1:iterations
    [input,f_optimum(i)]=ga(@stalagmite_function,2,[],[],[],[],[0;0],[0.6;0.6]);
    x_optimum(i)=input(1);
    y_optimum(i)=input(2);
end
study_time_2=toc

figure(2)
subplot(2,1,1)
surfc(xx,yy,-f)
xlabel('x-values')
ylabel('y-values')
title('Study-2 (Statistical behavior with upper and lower bounds)')
shading interp
hold on;
plot3(x_optimum,y_optimum,-f_optimum,'marker','o');
subplot(2,1,2)
plot(-f_optimum);
xlabel('No. of Iterations')
ylabel('Maximum function value')

%Study-3: Increasing GA iterations (Population size-250)

options=optimoptions('ga');     	%Create optimization options
options=optimoptions(options,'populationsize',250)

tic
for i=1:iterations
    [input,f_optimum(i)]=ga(@stalagmite_function,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
    x_optimum(i)=input(1);
    y_optimum(i)=input(2);
end
study_time_3=toc

figure(3)
subplot(2,1,1)
surfc(xx,yy,-f)
xlabel('x-values')
ylabel('y-values')
title('Study-3 (Increased ga iterations (Population size-250))')
shading interp
hold on;
plot3(x_optimum,y_optimum,-f_optimum,'marker','o');
subplot(2,1,2)
plot(-f_optimum);
xlabel('No. of Iterations')
ylabel('Maximum function value')

% To display the optimum values of x and y
display(input)

% End of program

    

Output (From Command Window):

study_time_1 =

    1.1212

study_time_2 =

    1.6034


options = 

  ga options:

   Set properties:
                  PopulationSize: 250

   Default properties:
             ConstraintTolerance: 1.0000e-03
                     CreationFcn: @gacreationuniform
                    CrossoverFcn: @crossoverscattered
               CrossoverFraction: 0.8000
                         Display: 'final'
                      EliteCount: '0.05*PopulationSize'
                    FitnessLimit: -Inf
               FitnessScalingFcn: @fitscalingrank
               FunctionTolerance: 1.0000e-06
                       HybridFcn: []
         InitialPopulationMatrix: []
          InitialPopulationRange: []
             InitialScoresMatrix: []
                  MaxGenerations: '100*numberOfVariables'
             MaxStallGenerations: 50
                    MaxStallTime: Inf
                         MaxTime: Inf
                     MutationFcn: {@mutationgaussian  [1]  [1]}
    NonlinearConstraintAlgorithm: 'auglag'
                       OutputFcn: []
                         PlotFcn: []
                  PopulationType: 'doubleVector'
                    SelectionFcn: @selectionstochunif
                     UseParallel: 0
                   UseVectorized: 0

study_time_3 =

    5.4338


input =

    0.0668    0.0668

>> 

Output (From Plot):

Study-1

From the above plot we can see that some of our x and y values are out of define boundary conditions (x and y values should be between 0 and 0.6). In other words, some of x and y values are away from salagmite suface. So we failed to reach global maxima in this case. To get global maxima we have to set the bound values which wil be Study-2.

Total study time taken is 1.1212 second.

Study-2

In this study we set upper and lower bound values of x and y in order to get optimum values of x and y. This study gave the better results compare to previous one but not enough to get global maxima. From the plot we are getting four point, which means that our global maxima is lying under the boundary of these four points. So, far more we come up to one concluion that that if we increased the population size than we can get global maxima.

Total study time taken is 1.6034 second.

Study-3

In study 3, we increased the population size to get the global maxima. In ga, it takes by default population size 50. From the population size of 50 we were unable to get the global maxima so it was necessary to increased to higher value for study. Here, we take population size of 250 and we sucessfully get our global maxima.

Total study time taken is 5.4338 second.

I would like to add one more point that, more the population size will increases the time taken in study. It can easily we compared from all three studies.

Errors:

One error was found while executing the program.

Solution of errors: After examing the code, I found out that the error was showing because there was some mistake in my salagmite function (i.e formula). So, after making the necessary correction the problem get solved.

No error was found after that and program run successfully.

References:

https://www.tutorialspoint.com/genetic_algorithms/index.htm

https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3

https://skill-lync.com/knowledgebase/genetic-algorithm-explained

https://in.mathworks.com/help/gads/ga.html

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.