Skip to content

Instantly share code, notes, and snippets.

@summivox
Last active March 18, 2016 13:02
Show Gist options
  • Save summivox/6f1d93f50709560da9c3 to your computer and use it in GitHub Desktop.
Save summivox/6f1d93f50709560da9c3 to your computer and use it in GitHub Desktop.
Prepare a Simulink model for repeated parameterized simulation in Rapid Accelerator mode.
function f_para = cmaes_parallelize(f_orig)
f_para = @f;
function scores = f(vs)
n = size(vs, 2);
scores = zeros(1, n);
parfor i = 1:n
scores(i) = f_orig(vs(:, i));
end
end
end
function f_sim = rtp_sim_wrapper(model, param_init)
% Prepare a Simulink model for repeated parameterized simulation in Rapid
% Accelerator mode.
%
% model: name/handle of the Simulink model
% param_init: struct mapping parameters to their default values
%
% f_sim: (opt, param) -> out
% simulate the model (by calling `sim`) with given parameters
%
% opt: struct containing options to be passed into `sim`
% param: struct mapping parameters to their values
%
% out: return value of `sim`
load_system(model);
% set parameters to tunable
ws = get_param(model, 'ModelWorkspace');
param_names = fieldnames(param_init).';
param_n = length(param_names);
for i = 1:param_n
name = param_names{i};
ws.clear(name);
o = Simulink.Parameter;
o.Value = param_init.(name);
o.CoderInfo.StorageClass = 'SimulinkGlobal';
assignin('base', name, o);
end
% compile
rtp_init = Simulink.BlockDiagram.buildRapidAcceleratorTarget(model);
% cleanup
try ws.reload; catch; end
evalin('base', ['clear ', strjoin(param_names, ' ')]);
% create sim closure
f_sim = @f;
function out = f(opt, param)
rtp = rtp_assign(rtp_init, param); % fast impl
opt.SimulationMode = 'rapid';
opt.RapidAcceleratorUpToDateCheck = 'off';
opt.RapidAcceleratorParameterSets = rtp;
out = sim(model, opt);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment