genetic algorithm for stalagmite function
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.You can apply the genetic algorithm to solve 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 differs from a classical, derivative-based, optimization algorithm in two main ways, as summarized in the following table.
in this project the first most important logic was to understand how to calculate the global maxima.
firstly, i created a function that works according to the problem provied to us in the assignment.
the problem had 4 equations and i created up a function named as stalagmite.m
the code is shown below:-
function [f] = stalagmite(input_vector)
f1x = (sin(5.1.*pi.*input_vector(1) + 0.5)).^6;
f1y = (sin(5.1.*pi.*input_vector(2) + 0.5)).^6;
f2x = exp((-4*log(2)*(input_vector(1)-0.0667).^2)/0.64);
f2y = exp((-4.*log(2).*(input_vector(2)-0.0667).^2)./0.64);
ff = f1x .* f1y .* f2x .* f2y;
f = -ff;
end
here, i have taken the values of x&y as input vectors. as shown above in the code.
this function is called as many times we require without writing the entire code agagin and again.
the global maxima is found by putting a neagtive sign behind the ga algorithm which returns the inverese of global minima.
the code is shown below:
close all
clear all
clc
%Preparing the data
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num = 100;
f = get_stalagmite(x,y);
options = optimoptions(\'ga\');
options = optimoptions(options,\'Populationsize\',300);
%study1
tic
for i=1:num
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1],[],[],options);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
time = toc
subplot(2,1,1)
surfc(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,\'marker\',\'o\',\'markersize\',5)
title(\'unbounded inputs\')
subplot(2,1,2)
plot(fopt)
xlabel(\'number of Iterations\')
ylabel(\'Function Minization\')
plot(fopt)
%sub code
%get_stalagmite.m
function [f]=get_stalagmite(x,y)
%preparing the Data in 2D mesh
[xx, yy] = meshgrid(x,y);
%Evaluating Stalagemite 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
end
thank you!