Global variables are forbidden in parallel multistart optimization

7 ビュー (過去 30 日間)
Kun Yang
Kun Yang 2021 年 10 月 25 日
コメント済み: Kun Yang 2021 年 10 月 28 日
I have met a problem when I try to use MultiStart optimization in parallel. I would like to rise this question here, asking for help and also making the concept clearer for others.
Basic info:
I am using MultiStart optimization toolbox, my MATLAB version is R2021a. Thanks to my university.
However, my optimization ends with positive exitflag when I turn off the parallel option and always ends with exitflag=-10 when I turn on it.
As you may easily find out, -10 exitflag means user defined function has bugs. But this cannot make sense as my function goes well with single pool.
Later on, after searching in many different ways, I finally found out that the bug is the global variable. MATLAB parallel MultiStart optimization toolbox cannot support global variables in user defined functions. I have tried a demo case for example, which proves my idea.
In another word, the parallel MultiStart cannot allow functions to access global variables. The function should be totally independent. But in my case, I need to read in a large dataset in previous and I will use the dataset during my calculation. Obviously, I cannot let the objective function to read in the dataset in every trial, which may be extremely time consuming. Actually, I do not have to change my dataset in functions but the program was killed just because I try to access the global variables, which is really annoying.
Any ideas? Hope someone could save my poor codes.
Demo example:
main code:
clc;
clear all;
format long;
x0 = [2,3];
global A
A=10;
problem=createOptimProblem('fminunc',...
'objective',@usrobj,...
'x0',x0,'options',...
optimoptions(@fminunc,'Algorithm','quasi-newton'));
[xf,fval]=fminunc(problem);
%%
ms = MultiStart('UseParallel',true,'Display','iter');
parpool
[xf2,fval2,eflag,output,manymins]=run(ms,problem,50);
delete(gcp('nocreate'))
user defined objective function:
function f=usrobj(x)
global A
%A=evalin('base','A'); % evalin has the same problem
f=A+x(1)^2+x(2)^2-A*(cos(2*pi*x(1))+cos(2*pi*x(2)));
end

採用された回答

Alan Weiss
Alan Weiss 2021 年 10 月 26 日
There are other ways to pass variables other than declariig them as global. See Passing Extra Parameters.
Alan Weiss
MATLAB mathematical toolbox documentation
  1 件のコメント
Kun Yang
Kun Yang 2021 年 10 月 28 日
Dear Alan,
Thank you again! I didn't realize the usage and value of Anonymous Functions the first time I saw it. My code can run in parallel now with Anonymous Functions as objective function and constraint function. Thank you very much for your support!
Kun

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by