'UseParallel' with particleswarm() when objective function calls Simulink model

Hello,
I am optimizing some simulink model parameters using particleswarm().
I do not have experience with parallel computing, but I believe I reached the moment when I need it...
I would like to get some advice on what I need to change in my objective function so that it works in parallel (serial computing runs with no errors)
My main code is:
close all
clear
clc
% Define global variable with model name
global mdl;
mdl='Sim_exp';
% Load parameters to base workspace
sim_init_exp;
% Set upper and lower bounds on optimization parameter
lb_gains = [0 0];
ub_gains = [50 50];
% Solver options
options = optimoptions('particleswarm');
options = optimoptions(options,'UseParallel',true);
options = optimoptions(options,'PlotFcn', { @pswplotbestf });
% Run PSO
[opt_PI,~,~,~] = particleswarm(@obj_fcn,2,lb_gains,ub_gains,options);
my objective function is:
function [out] = obj_fcn(K)
% Access global variable
global mdl;
% Change parameter values in base workspace
assignin('base','Kp',K(1))
assignin('base','Ki',K(2))
% Simulate model
sim(mdl);
% Load results
ref1=curr_refs.Data(:,1);
ref2=curr_refs.Data(:,2);
meas1=curr_meas.Data(:,1);
meas2=curr_meas.Data(:,2);
ang1=alpha_angles.Data(:,1);
ang2=alpha_angles.Data(:,2);
mid=round(length(ref1)/2);
% Compute objective function value
fa1=trapz(abs(ref1-meas1))+trapz((ref1-meas1).^2);
fa2=trapz(abs(ref2-meas2))+trapz((ref2-meas2).^2);
fb11=abs(ref1(1)-max(meas1(1:mid)))+abs(ref1(end)-max(meas1(mid:end)));
fb12=abs(ref1(1)-min(meas1(1:mid)))+abs(ref1(end)-min(meas1(mid:end)));
fb21=abs(ref2(1)-max(meas2(1:mid)))+abs(ref2(end)-max(meas2(mid:end)));
fb22=abs(ref2(1)-min(meas2(1:mid)))+abs(ref2(end)-min(meas2(mid:end)));
out=((fa1+fa2)*1e-4)+fb11+fb12+fb21+fb22;
end
From the errors I get when I try to run this code with 'UseParallel' true, it seems I should also parallelize the simulation inside my objective fcn, but I don't know where to start.
Could you please advise?

1 个评论

Could you post the error message that you are getting?
As a first guess for troubleshooting, I would consider getting rid of that global variable and just passing it directly into the function. See many answers related to this issue:
https://www.mathworks.com/matlabcentral/answers/?term=global+variables+parfor

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Manual Performance Optimization 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by