Week 4.1 - Genetic Algorithm
objective:
Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function
clear all
close all
clc
%definiing our search spaces
x=linspace(0,0.6,150);
y=linspace(0,0.6,150);
%creating 2d mesh
[xx yy]=meshgrid(x,y);
%evaluating the stalagimite 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
figure(1)
surf(xx,yy,f);
shading interp
xlabel('x range');
ylabel('y range');
% case1
for i=1:50
[input,fval(i)]=ga(@stalagmite,2);
end
figure(2)
plot(fval)
axis([1 50 -1 0])
title('without any boudary limit run gentic algoritham');
xlabel('x range');
ylabel('y range')
%case2
for i=1:50
[input,fval(i)]=ga(@stalagmite,2,[],[],[],[],[0 0],[0.6 0.6]);
end
figure(3)
plot(fval)
axis([1 50 -1 0])
title('with boudary limit run gentic algoritham');
xlabel('x range');
ylabel('y range')
%Case3
option = optimoptions('ga','PopulationSize',250);
for i=1:50
[input,fval(i)]=ga(@stalagmite,2,[],[],[],[],[0 0],[0.6 0.6],[],[],option);
end
figure(4)
plot(fval)
axis([1 50 -1 0])
title('with boudary limit and population size run gentic algoritham');
xlabel('x range');
ylabel('y range')
%stalagmite function created
function A=stalagmite(input_vector);
x=input_vector(1);
y=input_vector(2);
t1=(sin(5.1*pi*x+0.5))^6;
t2=exp((-4*log(2)*((x-0.0667)^2))/0.64);
t3=(sin(5.1*pi*y+0.5))^6;
t4=exp((-4*log(2))*((y-0.0667)^2)/0.64);
A=-(t1*t2*t3*t4);
end
code logic:
first by using clear all close all and clc all the previous data is cleared and then by defining our search spaces x and y by using linspace command and then by using mesg grid command we converted the one dimensional array to two dimesional; array we have to create the stalagmite function and attached at the end of code by using formula the formula to evluate the stalagmate the function two for loops are taken for each one i value the internal loop excuted j times by intializing the raange of j and i the we store the corresponding two dimensional values in variables (input_vectors) for xx(i,j) and yy(i,j) at end we created the function f(i,j) which contaions two dimesinal values of xx and yy such thatt for each xx(i) all yy(j) values are stored
then by using surf command we polt the xx ,yy then we obtain three dimensional figures
of the function shading interp command is used to remove shading 3dpictures
now we have to take another three figures so that
1.for figure 2
we take the for loop in some range
and we write the sintax for genetic algorithm to obation the global max maximum value but not defining any boundary or population size
%[input,fval(i)]=ga(@stalagmite,2)
and we plot the fval by using plot command and fixing the axis
2.for figure 3
we take the for loop in some range
and we write the sintax for genetic algorithm to obation the global max maximum value by defining any boundary only
%[input,fval(i)]=ga(@stalagmite,2,[],[],[],[],[0 0],[0.6 0.6]);
and we plot the fval by using plot command and fixing the axis
3.for figure 4
we take the for loop in some range
and we write the sintax for genetic algorithm to obation the global max maximum value by defining any boundary only
%option = optimoptions('ga','PopulationSize',250);
%for i=1:50
%[input,fval(i)]=ga(@stalagmite,2,[],[],[],[],[0 0],[0.6 0.6],[],[],option);
%end
and we plot the fval by using plot command and fixing the axis
errors faced:

i forget the use paranthensis and i used sqare brackets so i fouund error
i correct it and then evaluated to mnext step
error2:

while giving poopulation size and boundary range in syntax of genetic algoritham i forget to give to give exact syntax therefore i found eror after i found this i rectify my error.
output:
figure1:

figure2:to find globalmaxmima without any boundary limit by using genetic algorithm

figure3:to find gllobalmaxima with boundary limit by using genetic algorithm

figure4:to find gllobalmaxima with boundary limit and population size by using genetic algorithm
How genetic algorithm works breifly:
-
The algorithm begins by creating a random initial population.
-
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:
-
Scores each member of the current population by computing its fitness value. These values are called the raw fitness scores.
-
Scales the raw fitness scores to convert them into a more usable range of values. These scaled values are called expectation values.
-
Selects members, called parents, based on their expectation.
-
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.
-
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—cross over.
-
Replaces the current population with the children to form the next generation.
-
-
The algorithm stops when one of the stopping criteria is met.
*Stopping Conditions for the Algorithm
The genetic algorithm uses the following options to determine when to stop. See the default values for each option by running
opts = optimoptions('ga').-
MaxGenerations— The algorithm stops when the number of generations reachesMaxGenerations. -
MaxTime— The algorithm stops after running for an amount of time in seconds equal toMaxTime. -
FitnessLimit— The algorithm stops when the value of the fitness function for the best point in the current population is less than or equal toFitnessLimit. -
MaxStallGenerations— The algorithm stops when the average relative change in the fitness function value overMaxStallGenerationsis less thanFunction tolerance. -
MaxStallTime— The algorithm stops if there is no improvement in the objective function during an interval of time in seconds equal toMaxStallTime. -
FunctionTolerance— The algorithm runs until the average relative change in the fitness function value overMaxStallGenerationsis less thanFunction tolerance. -
ConstraintTolerance— TheConstraintToleranceis not used as stopping criterion. It is used to determine the feasibility with respect to nonlinear constraints. Also,max(sqrt(eps),ConstraintTolerance)determines feasibility with respect to linear constraints.
The algorithm stops as soon as any one of these conditions is met.
using multiple iterations -
- There are conflicting reports of the advantage of using one or multiple independent runs. This problem has consequences on parallel GAs with isolated populations and also to determine when random search can outperform a GA. Under a constraint of fixed cost and assuming no mutation,the analysis showed that the expected quality of the solution reached by multiple independent small runs is higher than the quality reached by a single large run only invery limited conditions. In particular, multiple runs seem advantageous at versmall population sizes, which result in solutions of poor quality, and close to asaturation point where the solution quality does not improve with increasinglylarger populations. In addition, the greatest advantage of multiple independentruns is on short problems, and the advantage tends to decrease with higher BBorder. The results suggest that for difficult problems (long and with high-orderBBs), the best alternative is to use a single run with the largest populationpossible. Small independent runs should be avoided.
- syntax of gentic 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(___)
final result:
hence i find the global maxima of the function by declaring population size and boundary limit to get the value