Convert MATLAB code to PYTHON

71 views (last 30 days)
Emna
Emna on 31 Jan 2023
Answered: Priyank Pandey on 7 Mar 2023
Hello guys, i have a matlab code, i am a beginner in python so I found difficulties to convert it to a python code, could you please help me? Thank you :)
PS: The complete code is in the 1st comment
Code:
clc;close;
x=[1 10 2];
y=[2 5 5];
r=[1 2 0.3]
lb = [0,0,0]; % declaration de la borne inférieure
%
ub = [2*pi,2*pi,2*pi]; % declaration de la borne supérieure
dim=3; % declaration de la dimmension du vecteur x
N=100; % declaration de nombre population
Max_iteration=500; % decalaration de nombre d'iteration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Cercle function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = circle(x,y,r)
hold on
th = 0:pi/50:2*pi;
xunit = r * cos(th) + x;
yunit = r * sin(th) + y;
h = plot(xunit, yunit);
hold off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Objective function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x1=@(p)r(1).*cos(p(1))+x(1);
y1=@(p)r(1).*sin(p(1))+y(1);
x2=@(p)r(2).*cos(p(2))+x(2);
y2=@(p)r(2).*sin(p(2))+y(2);
x3=@(p)r(3).*cos(p(3))+x(3);
y3=@(p)r(3).*sin(p(3))+y(3);
objective = @(p)sqrt(1/3*((x1(p)-x2(p)).^2+(x1(p)-x3(p)).^2+(x2(p)-x3(p)).^2))+sqrt(1/3*((y1(p)-y2(p)).^2+(y1(p)-y3(p)).^2+(y2(p)-y3(p)).^2));%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%MFO algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[Best_flame_score,Best_pos3,Convergence_curve]=WSO(N,Max_iteration,lb,ub,dim,objective);
theta1=Best_pos3(1);
theta2=Best_pos3(2);
theta3=Best_pos3(3);
x1=r(1).*cos(theta1)+x(1);
y1=r(1).*sin(theta1)+y(1);
x2=r(2).*cos(theta2)+x(2);
y2=r(2).*sin(theta2)+y(2);
x3=r(3).*cos(theta3)+x(3);
y3=r(3).*sin(theta3)+y(3);
X=[x1 x2 x3]
Y=[y1 y2 y3]
Best_flame_score
figure;
plot(x,y,'*',X,Y,'*');
h=circle(x(1),y(1),r(1));
h1=circle(x(2),y(2),r(2));
h2=circle(x(3),y(3),r(3));
  2 Comments
the cyclist
the cyclist on 31 Jan 2023
This MATLAB code will be difficult to convert to python, because this code is itself confusing and ill-formed. Specifically,
  • it's not easy to be certain where subfunctions begin and end
  • the anonymous function objective is defined (and is an input to a subfunction), but is never used
  • the variable Best_pos3 appears as a function output, but I don't see that it is calculated anywhere
So, you might want to think about those things first.
That being said, I have found ChatGPT to be a surprisingly good tool for converting code from one language to another. (I have converted some moderately tricky statistical code from MATLAB to python.) You might want to create an OpenAI account, and give that a try (if you don't get a useful solution here).
Emna
Emna on 31 Jan 2023
@the cyclist the code is not complete.. but since it will be so long i just posted the part that I want to convert.. My idea is to use another solver instead of WSO which is TLBO in python, so I just kept the code I want to change.
And okay I will check the ChatGPT out :)
Here's the complete code( which contains 5 files)
Circle:
function h = circle(x,y,r)
hold on
th = 0:pi/50:2*pi;
xunit = r * cos(th) + x;
yunit = r * sin(th) + y;
h = plot(xunit, yunit);
hold off
Code1:
clc;close;
x=[1 10 2];
y=[2 5 5];
r=[0.2 2 0.6]
lb = 0; % declaration de la borne inférieure
%
ub = pi; % declaration de la borne supérieure
dim=3; % declaration de la dimmension du vecteur x
N=50; % declaration de nombre population
Max_iteration=500; % decalaration de nombre d'iteration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%declaration de la fonction objective
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x1=@(p)r(1).*cos(p(1))+x(1);
y1=@(p)r(1).*sin(p(1))+y(1);
x2=@(p)r(2).*cos(p(2))+x(2);
y2=@(p)r(2).*sin(p(2))+y(2);
x3=@(p)r(3).*cos(p(3))+x(3);
y3=@(p)r(3).*sin(p(3))+y(3);
objective = @(p)sqrt(abs(x1(p)-x2(p))+abs(x1(p)-x3(p))+abs(x2(p)-x3(p)))+sqrt(abs(y1(p)-y2(p))+abs(y1(p)-y3(p))+abs(y2(p)-y3(p)));%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% declaration de l'algorithme MFO
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[Best_flame_score,Best_pos3,Convergence_curve]=WSO(N,Max_iteration,lb,ub,dim,objective);
theta1=Best_pos3(1);
theta2=Best_pos3(2);
theta3=Best_pos3(3);
x1=r(1).*cos(theta1)+x(1);
y1=r(1).*sin(theta1)+y(1);
x2=r(2).*cos(theta2)+x(2);
y2=r(2).*sin(theta2)+y(2);
x3=r(3).*cos(theta3)+x(3);
y3=r(3).*sin(theta3)+y(3);
X=[x1 x2 x3]
Y=[y1 y2 y3]
Best_flame_score
figure;
plot(x,y,'*',X,Y,'*');
h=circle(x(1),y(1),r(1));
h1=circle(x(2),y(2),r(2));
h1=circle(x(3),y(3),r(3));
Initialization:
%___________________________________________________________________%
% Grey Wold Optimizer (GWO) source codes version 1.0 %
% %
% Developed in MATLAB R2011b(7.13) %
% %
% Author and programmer: Seyedali Mirjalili %
% %
% e-Mail: ali.mirjalili@gmail.com %
% seyedali.mirjalili@griffithuni.edu.au %
% %
% Homepage: http://www.alimirjalili.com %
% %
% Main paper: S. Mirjalili, S. M. Mirjalili, A. Lewis %
% Grey Wolf Optimizer, Advances in Engineering %
% Software , in press, %
% DOI: 10.1016/j.advengsoft.2013.12.007 %
% %
%___________________________________________________________________%
% This function initialize the first population of search agents
function Positions=initialization(SearchAgents_no,dim,ub,lb)
Boundary_no= size(ub,2); % numnber of boundaries
% If the boundaries of all variables are equal and user enter a signle
% number for both ub and lb
if Boundary_no==1
Positions=rand(SearchAgents_no,dim).*(ub-lb)+lb;
end
% If each variable has a different lb and ub
if Boundary_no>1
for i=1:dim
ub_i=ub(i);
lb_i=lb(i);
Positions(:,i)=rand(SearchAgents_no,1).*(ub_i-lb_i)+lb_i;
end
end
RMSE:
function RMSE=RMSE(o,p)
% (o - p) % Errors
% (o - p).^2 % Squared Error
% mean((o - p).^2) % Mean Squared Error
RMSE = sqrt(mean((o - p).^2));
end
WSO:
%% Dr.Tummala.S.L.V.Ayyarao
%% https://scholar.google.co.in/citations?user=X7i25FAAAAAJ&hl=en&oi=sra
%% GMR Institute of Technology, India
%% Ayyarao, TummalaS LV, N. S. S. RamaKrishna, Rajvikram Madurai Elavarasam, Nishanth Polumahanthi, M. Rambabu, Gaurav Saini, Baseem Khan, and Bilal Alatas. "War Strategy Optimization Algorithm: A New Effective Metaheuristic Algorithm for Global Optimization." IEEE Access (2022).
%% https://ieeexplore.ieee.org/abstract/document/9718247
%% Code developed by Tummala.S.L.V.Ayyarao
%% Ayyarao, Tummala SLV, and Polamarasetty P. Kumar. "Parameter estimation of solar PV models with a new proposed war strategy optimization algorithm." International Journal of Energy Research (2022).
%% https://onlinelibrary.wiley.com/doi/abs/10.1002/er.7629
%% Improved version of the code will be updated soon
function [King_fit,King,Convergence_curve]=WSO(Soldiers_no,Max_iter,lb,ub,dim,fobj)
% global W1 fitness_history position_history Trajectories l
% fitness_history=zeros(Soldiers_no,Max_iter);
% position_history=zeros(Soldiers_no,Max_iter,dim);
% initialize alpha, beta, and delta_pos
King=zeros(1,dim);
King_fit=inf;
Positions=initialization(Soldiers_no,dim,ub,lb);
pop_size=size(Positions,1);Convergence_curve=zeros(1,Max_iter);
Positions_new=zeros(size(Positions));
fitness_old=inf*ones(1,pop_size);
fitness_new=inf*ones(1,pop_size);
l=1;% Loop counter
W1=2*ones(1,pop_size);
Wg=zeros(1,pop_size);
Trajectories=zeros(Soldiers_no,Max_iter);
% Main loop
R=0.8;
for j=1:size(Positions,1)
fitness=fobj(Positions(j,:));
fitness_old(j)=fitness;
if fitness<King_fit
King_fit=fitness;
King=Positions(j,:);
end
end
while l<Max_iter
% l
[~,tindex]=sort(fitness_old);
Co=Positions(tindex(2),:);
iter =l;
com=randperm(pop_size);
for i=1:pop_size
RR=rand;
if RR<R
D_V(i,:)=2*RR*(King-Positions(com(i),:))+1*W1(i)*rand*(Co-Positions(i,:));
else
D_V(i,:)=2*RR*(Co-King)+1*rand*(W1(i)*King-Positions(i,:));
end
Positions_new(i,:)=Positions(i,:)+D_V(i,:);
Flag4ub=Positions_new(i,:)>ub;
Flag4lb=Positions_new(i,:)<lb;
Positions_new(i,:)=(Positions_new(i,:).*(~(Flag4ub+Flag4lb)))+ub.*Flag4ub+lb.*Flag4lb;
fitness=fobj(Positions_new(i,:));
fitness_new(i) = fitness;
if fitness<King_fit
King_fit=fitness;
King=Positions_new(i,:);
end
% Co
if fitness<fitness_old(i)
Positions(i,:)=Positions_new(i,:);
fitness_old(i)=fitness;
% else
Wg(i)=Wg(i)+1;
W1(i)=1*W1(i)*(1-Wg(i)/Max_iter)^2;
end
% [~,tindex1]=max(fitness_old);
% Positions(tindex1,:)=lb+rand*(ub-lb);
% W1(tindex1)=0.5;
end
if l<1000
[~,tindex1]=max(fitness_old);
Positions(tindex1,:)=lb+rand*(ub-lb);
% Positions(tindex1,:)=(1-randn(1))*(King-median(Positions(1:pop_size,:)))+Positions(tindex1,:);
% Positions(tindex1,:)=rand*King;
% W1(tindex1)=0.5;
end
l=l+1;
Convergence_curve(l)=King_fit;
end

Sign in to comment.

Answers (1)

Priyank Pandey
Priyank Pandey on 7 Mar 2023
Hi Emna,
To convert MATLAB code to Python follow the following steps:
Step 1: Develop your own MATLAB Code as MATLAB Function
Step 2: Enter the command on command window
command:
deploytool
Step 3:
Select python package
Step 4:
Export your package
Follow the bellow link to have a better understanding on how to convert MATLAB Code to Python:
https://in.mathworks.com/help/compiler_sdk/gs/create-a-python-application-with-matlab-code.html

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!