I have an optimization task where the cost function includes a Simulink Model which is set to run in Rapid Accelerator Mode.
Now I like to use parallel optimization for my genetic algorithm (ga).
How do I set this up?
What I tried is the following:
model = 'Model14';open_system(model);options = optimoptions('ga', 'UseParallel', true);nvars = 4;A = [];b = [];Aeq = []; %no constraint
beq = []; lb = [1e5 10 2 20];ub = [8.5e5 4e6 50 40];nonlcon = [];[x, fval, output] = ga(@costfct_optim, nvars, A, b, Aeq, beq, lb, ub, nonlcon, options);
The cost function (costfct) looks as follows:
function ctot = costfct_optim(x)plim = x(1);ebat = x(2);h = x(3);Tthres = x(4);model = 'Model14';in = Simulink.SimulationInput(model);in = in.setModelParameter('SimulationMode', 'rapid');in = in.setVariable('limgain', plim);in = in.setVariable('Ebatgain', ebat);in = in.setVariable('hgain', h);in = in.setVariable('Tthres', Tthres);out = sim(in);T_eol = out.yout{1}.Values.Time(end)/3600/24/365;Etot = out.yout{1}.Values.Data(end)/3.6e6/T_eol;[ctot, ~, ~, ~] = costfct(plim, ebat, T_eol, Etot);
This does not work. I guess this is because there is no setup function supplied, which I use when combining parallel simulations with Rapid Accelerator outside optimization tasks.
The line would look as follows:
out = parsim(in, 'ShowProgress', 'on', ... 'SetupFcn', @() sldemo_parallel_rapid_accel_sims_script_setup(model));
Including this line in the cost function for the optimization task does not work. I guess this is because in that case every single cost function evaluation would try to set up a separate parallel simulation.
For completeness, the error I am getting with the first two pieces of code:
>> opt_ga### Building the rapid accelerator target for model: Model14### Successfully built the rapid accelerator target for model: Model14Starting parallel pool (parpool) using the 'local' profile ...Connected to the parallel pool (number of workers: 8).### Build procedure for Model14 aborted due to an error.Error using costfct_optim (line 21)Unable to build a standalone executable to simulate the model 'Model14' in rapid accelerator mode.Error in createAnonymousFcn>@(x)fcn(x,FcnArgs{:}) (line 11)fcn_handle = @(x) fcn(x,FcnArgs{:});Error in fcnvectorizer (line 16) parfor (i = 1:popSize)Error in makeState (line 63) Score = fcnvectorizer(state.Population(initScoreProvided+2:end,:),FitnessFcn,1,options.SerialUserFcn);Error in galincon (line 17)state = makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);Error in ga (line 401) [x,fval,exitFlag,output,population,scores] = galincon(FitnessFcn,nvars, ...Error in opt_ga (line 41)[x, fval, output] = ga(@costfct_optim, nvars, A, b, Aeq, beq, lb, ub, nonlcon, options);Caused by: Error using Simulink.Simulation.internal.DesktopSimHelper.sim Dot indexing is not supported for variables of this type. Failure in user-supplied fitness function evaluation. GA cannot continue.
Best Answer