Global variables are forbidden in parallel multistart optimization

11 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Alan Weiss
Alan Weiss el 26 de Oct. de 2021
There are other ways to pass variables other than declariig them as global. See Passing Extra Parameters.
Alan Weiss
MATLAB mathematical toolbox documentation
  1 comentario
Kun Yang
Kun Yang el 28 de Oct. de 2021
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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Solver Outputs and Iterative Display en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by