Challenge

Week 4.1 - Genetic Algorithm

Code Explination:

Note a huge part of the code is explained within the program:

1) After generating the X and Y meshgrid they are used as counters and this each value of the meshgrid generates the vectors that are used by stalgamite function

2)thus the for loop performs the required number of iterations. using this the countors for all the plots to be generated are formed.

3) then in the 3 cases the ga function is used for the optimization . this is used to find the maximum value in the plots. 

 4) the three cases show the variations that can be made in the ga to increase the accuracy with which the optimization can be performed. we can see that the number of max points attained areduces to 1 as we come to the 3rd case and the optimisation value reaches 1.

Stalagmite function:

this function is used to determine and understand the ga function . in this cade at the end f value is made negative to obtain the maximization function . this is done as the ga function by default fainds the minimization .

Errors:

1) initially struggled to make the make and understand the code required for the loops and how to make them work correctly.

2) Ploting the points correctly in the 3 axis system , used foptions instead of foutputs in plots making it form in a different way.

3) Made small mistakes with plotting methodes and variables.

clc
clear 
close all


genetic algorithm using Stalgamite as the function
% The stalgmite is a basic function that can be used to determine and
% evaluate and understand the genetic plots.

x = linspace(0,0.6,150); % this creates a vector containing 150 values between 0 and 0.6.
y = linspace(0,0.6,150); % NOTE: hear its important to understand that the max value is 0.6
[X ,Y] = meshgrid(x,y);  % this function makes a  2 matrix grid X and Y of 150x150 rowsa and colums 

n = 50; % this is the max iterations required to perform for this problem.


To make the initial Plot
% This generates the 3D plot
tic % this is a function that starts the stop watch
f = zeros(1,n);
for i = 1:length(X)      % the i loops 1 to 150 times generating the values
    for j = 1:length(Y)  % the j loops 1 to 150 and also as its within the i loop repeating it 22500
        vector(1) = X(i,j); % returnes each value of the matrix X to calculate in the function 
        vector(2) = Y(i,j); % returnes each value of the matrix Y to calculate in the function
        f(i,j) = genetical(vector); % Using this new values are computed and a 150x150 matrix grid is made and saved as f
        % this new values of f is in z direction giving the maximum of the
        % curve 
    end
end

time_1 = toc % this outputs the time taken by the above loop to run

surfc(X,Y,-f);  % this is used to make a surface plot in the 3 axis system
shading interp; % the shading interp removes the mesh grid lines and makes a smooth plot.
Maximum1 = max(-f(:)) % the max value in the z direction is given 
xlabel('x');
ylabel('y');
zlabel('f');
title('Initial surface plot');
% above lines of code is made for astetics

Case 1: Using the ga function to optimise the given function
% the genetic algorith function is a predefined function that is used for
% optimization . this function can use anywhere from 1 input to 11 inputs
% based onall available and required parameters defined in the function.
% This is one of the most commonly used optimisation functions based upon
% darvins theory of evolution 
% But this function is mainly used for minimization operations as its the
% default settings that is returned back.
tic
xoutput = zeros(1,n);
youtput = zeros(1,n);
foutputs =zeros(1,n);
% the above three lines of code is used to preallocate the data to reduce
% the time required for calculation this is done so that a new slot to
% store the data and repeate this process within the loop can be omitted.
for k = 1:n
    [inputs,foutputs(k)] = ga(@genetical,2); % hear the ga is using the 2 variables vector(1,2) i.e. x and y values and returns the inputs and f outputs saving the data.
    xoutput(k) = inputs(1); 
    youtput(k) = inputs(2);
end
% in the above loop using the initial values the ga is run for the given
% function finding the optimal value 
% this generates an unbound statistical behaviour meaning that there are no
% boundaries or algorithms used togenerate the plots. only the function
% hear is used to generate the stalagmite plot .

maximum2 = max(-foutputs) % to give the max value output after o

time_2 = toc;

    figure(1); % saves the figures for the first plots 
    subplot(2,1,1); % sub plot is used to split and display multiple plots in a single figure. the division ina matrix method.
    
    surfc(X,Y,-f); % creates the 3d surface 
    hold on;
    shading interp;% the shading interp removes the mesh grid lines and makes a smooth plot.
    plot3(xoutput,youtput,-foutputs,"Marker","o","MarkerSize",5,"MarkerFaceColor","r");
    
    % The above plot3 marks the points and connects all the points in the output vectors of x y f generated  
    
    xlabel('x');
    ylabel('y');
    zlabel('f');
    title('Case1 surface plot');
    grid on;
    % the hold and grid ,label commands are used to make the graphs more appeling 
    subplot(2,1,2);
    plot(-foutputs);
    xlabel('iterations');
    ylabel('Function minimum value');
    

Case 2: 8 input values are used , lower and upper bound values play a majour role 

% 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.)
    
tic 
 for l = 1:n
     [inputs,foutputs(l)]=ga(@genetical,2,[],[],[],[],[0;0],[0.55;0.55]); % Thus the iterations are restricted to calculate from 0 to 0.55
     xoutput(l) = inputs(1);
     youtput(l) = inputs(2);
 end
 
 maximum3 = max(-foutputs) % hear we see that the foutput value has reached 1 which is the maximum. meaning 100% optimisation has been obtained
 
 % It can be seen hear that in the graphs generated the 4 heighest peaks
 % are returned and plotted in the graph
 time_2 = toc
 
    figure(2);
    surfc(X,Y,-f);
    hold on
    shading interp;
    plot3(xoutput,youtput,-foutputs,"Marker","o","MarkerSize",5,"MarkerFaceColor",'r');
    xlabel('x');
    ylabel('y');
    zlabel('f');
    title('Case2 surface plot');
    subplot(2,1,1);
    hold on;
    surfc(X,Y,-f);
    shading interp;
    plot3(xoutput,youtput,-foutputs,"Marker","o","MarkerSize",5,"MarkerFaceColor",'r');
    xlabel('x');
    ylabel('y');
    title('Top view of surface plot showing max points');
    grid on;
    subplot(2,1,2);
    plot(-foutputs);
    xlabel('iterations');
    ylabel('function minimum value');
    
    % the above lines of code like all other cases are used to generate the
    % plots and visvalise the values.
    
    
    

Case 3:  To this case , options is added to increase the population size.
% by increasing the population size, by doing so the variations to gain an more accurate calculation is increased 


tic
options = optimoptions('ga',"PopulationSize",300)


for m = 1:n
      [inputs,foutputs(m)]=ga(@genetical,2,[],[],[],[],[0;0],[1;1],[],[],options);
     xoutput(m) = inputs(1);
     youtput(m) = inputs(2);
end

maximum4 = max(-foutputs)
% it is alos seen hear that 100%optimisation is reached 

time_3 = toc

figure(3)
    surfc(X,Y,-f);
    hold on
    shading interp;
    plot3(xoutput,youtput,-foutputs,"Marker","o","MarkerSize",5,"MarkerFaceColor",'r');
    xlabel('x');
    ylabel('y');
    zlabel('f');
    title('Case3 surface plot');
    subplot(2,1,1);
    hold on;
    surfc(X,Y,-f);
    shading interp;
    plot3(xoutput,youtput,-foutputs,"Marker","o","MarkerSize",5,"MarkerFaceColor",'r');
    xlabel('x');
    ylabel('y');
    title('Top view of surface plot showing max points');
    grid on;
    subplot(2,1,2);
    plot(-foutputs);
    xlabel('iterations');
    ylabel('function minimum value');
 


   
%%Stalgamite Functione code:

function [f] = genetical(vector)
    
    x = vector(1);
    y = vector(2);
    % hear 1 and 2 represent the two variables for the function and save
    % them seperately to x and y
    f1x = (sin(5.1*pi*x+0.5)).^6;
    f1y = (sin(5.1*pi*y+0.5)).^6;
    % therefor the above f10 f11 f12 f13 ....f1150
    t1 = ((x-0.0667).^2)/(0.64);
    f2x = exp(-4.*log(2)*t1);
    
    t2 = ((y-0.0667).^2)/(0.64);
    f2y = exp(-4.*log(2)*t2);
    
    f = -(f1x.*f2x.*f1y.*f2y);
end
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.