Global variables are forbidden in parallel multistart optimization

조회 수: 13 (최근 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개)

카테고리

Help CenterFile Exchange에서 Global or Multiple Starting Point Search에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by