Challenge

Week 4.1 - Genetic Algorithm

AIM:

To write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.

INTRODUCTION:
A stalagmite is a type of rock formation that rises from the floor of a cave due to the accumulation of material deposited on the floor from ceiling drippings.

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

FORMULAE:

FUNCTION CODE:

function [f]= stalagmite(input_vector)

x = input_vector(1);
y = input_vector(2);

%formula given
f1x = (sin((5.1*pi*x)+ 0.5)).^6;
f2y= (sin((5.1*pi*y)+0.5)).^6;
f3x = exp((-4*log(2)).*(x-0.0667)^2/(0.64));
f4y = exp((-4*log(2)).*(y-0.0667)^2/(0.64));
f = -(f1x*f2y*f3x*f4y);

end

GENETIC ALGORITHM:

A genetic algorithm (GA) is a method for solving both constrained and unconstrained optimization problems based on a natural selection process that mimics biological evolution. The algorithm repeatedly modifies a population of individual solutions. At each step, the genetic algorithm randomly selects individuals from the current population and uses them as parents to produce the children for the next generation. Over successive generations, the population "evolves" toward an optimal solution.

WORKING OF GENETIC ALGORITHM:

The following outline summarizes how the genetic algorithm works:

  1. The algorithm begins by creating a random initial population.

  2. The algorithm then creates a sequence of new populations. At each step, the algorithm uses the individuals in the current generation to create the next population. To create the new population, the algorithm performs the following steps:

    1. Scores each member of the current population by computing its fitness value. These values are called the raw fitness scores.

    2. Scales the raw fitness scores to convert them into a more usable range of values. These scaled values are called expectation values.

    3. Selects members, called parents, based on their expectations.

    4. Some of the individuals in the current population that have lower fitness are chosen as elite. These elite individuals are passed to the next population.

    5. Produces children from the parents. Children are produced either by making random changes to a single parent—mutation—or by combining the vector entries of a pair of parents—crossover.

    6. Replaces the current population with the children to form the next generation.

  3. The algorithm stops when one of the stopping criteria is met.

  4. The algorithm takes modified steps for linear and integer constraints.

  5. The algorithm is further modified for nonlinear constraints.

CREATING NEXT GENERATION:

The genetic algorithm creates three types of children for the next generation:

  • Elite are the individuals in the current generation with the best fitness values. These individuals automatically survive to the next generation.

  • Crossover is created by combining the vectors of a pair of parents.

  • Mutation children are created by introducing random changes, or mutations, to a single parent.

The following schematic diagram illustrates the three types of children.

Mutation and Crossover explains how to specify the number of children of each type that the algorithm generates and the functions it uses to perform crossover and mutation.

Crossover Children

The algorithm creates crossover children by combining pairs of parents in the current population. At each coordinate of the child vector, the default crossover function randomly selects an entry, or gene, at the same coordinate from one of the two parents and assigns it to the child. For problems with linear constraints, the default crossover function creates the child as a random weighted average of the parents.

Mutation Children

The algorithm creates mutation children by randomly changing the genes of individual parents. By default, for unconstrained problems, the algorithm adds a random vector from a Gaussian distribution to the parent. For bounded or linearly constrained problems, the child remains feasible.

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.

Where,

nvars

Number of design variables

Aineq

A matrix for linear inequality constraints

Bineq

b vector for linear inequality constraints

Aeq

Aeq matrix for linear equality constraints

Beq

beq vector for linear equality constraints

lb

Lower bound on x

ub

Upper bound on x

nonlcon

Nonlinear constraint functions

solver

'ga'

options

Options created using optimoptions or an options structure

CODE TO FIND GLOBAL MAXIMA:

close all 
clear all 
clc

%inputs 
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
% no of iterations
n = 50;

%creating  2D
[xx,yy] = meshgrid(x,y);

%stalagamite code
tic 
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 
studytime = toc

figure(1)
surfc(xx,yy,-f)
shading interp
xlabel('x value')
ylabel('y value')

%study 1 staistical behaviour unbounded inputs
tic
for i = 1:n
    [inputs,fopt(i)] = ga(@stalagmite,2);
        xopt(i)= inputs(1);
        yopt(i)=inputs(2);
end 
studytime1 = toc

%plotting 
figure(2)
subplot(2,1,1)
hold on 
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','k')
title('unbounded points')
subplot(2,1,2)
plot(-fopt)
xlabel('Iteration')
ylabel('Function Maximum')


% study 2 for bounded inputs
tic
for i = 1:n
    [inputs,fopt(i)]= ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
    xopt(i)= inputs(1);
    yopt(i)= inputs(2);
end

%plotting 
figure(3)
subplot(2,1,1) 
surfc(x,y,-f)
hold on 
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','k')
title('bounded inputs');
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations');
ylabel('Function Maximum');
studytime2 = toc

%study 3 - Bounded points ; incresing GA inputs
options = optimoptions('ga')
options = optimoptions(options, 'populationsize',180)

tic
for i = 1:n
    [inputs , fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options)
    xopt = inputs(1);
    yopt = inputs(2);
end 

%plotting
figure(4)
subplot(2,1,1)
hold on 
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',8,'markerfacecolor','r')
title('Bounded Inputs with Higher Population')
subplot(2,1,2)
plot(-fopt)
xlabel('Iterations')
ylabel('Function Maximum')
Studytime3 = toc

Global_maxima = -fopt

OUTPUT :

GENERAL STALAGMITE:

STUDY 1 - FOR UNBOUNDED INPUTS:

studytime1 = 2.4325

Here we fix the no of iterations(n) as 50 and run it for random samples.

STUDY 2 - FOR BOUNDED INPUTS:

studytime2 = 3.4247

Here we fix the upper boundary and lower boundary and run the samples to find global maxima.

STUDY 3 - Optimization , increasing the population size (bounded inputs)

Studytime3 = 8.1971

We optimize the code and increase the population size to get global maxima.

ERROR FACED:

Type error - Gave a wrong function name

Correction:

CONCLUSION:

Thus, the global maxima have been found.

Generic algorithm(ga) is used to find optimized value for global maxima of stalagmite function.

REFERENCES:

https://in.mathworks.com/discovery/genetic-algorithm.html

https://in.mathworks.com/help/gads/how-the-genetic-algorithm-works.html

https://in.mathworks.com/help/gads/ga.html#bs08mt7-1_sep_budidgf-nvars

https://en.wikipedia.org/wiki/Stalagmite

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.