FMPy
FMPy copied to clipboard
Calling FMPy from Matlab (Usability Improvement)
Since we work a lot with Matlab, I was looking for a convenient way to execute FMUs from Matlab scripts without going the Simulink route. I found that calling FMPy directly from Matlab seems to work well and this example may be usefull for other users:
%% FMU Path + Outputs
% define filename
filename = 'mymodel.fmu';
%% Dump FMU info
% py.fmpy.dump(filename)
%% Get Model Description
model_description = py.fmpy.read_model_description(filename);
%% Print variable names
% This may take long (lots of variables)
% for i = 1 : length(model_description.modelVariables)
% disp(char(model_description.modelVariables{i}.name))
% end
%% Simulation Outputs
% Define outputs
outs = {
'some outputs'
}.';
%% Simulation
% define input arguments
pyarg = pyargs('output', outs, 'stop_time', 11);
% run simulation
result = py.fmpy.simulate_fmu(filename, pyarg);
%% Covert Results
res = cellfun(@(x) cell2mat(cell(x)),cell(result.tolist()),'UniformOutput',false);
res = vertcat(res{:});
%% Plot results
figure
plot(res(:,1), res(:,2))
The only inconvenient part is the need to convert the Python output structure back to a Matlab structure or matrix. Perhaps, this can be improved with an additional argument in the simulate_fmu function, to provide a more Matlab friendly output structure.
I have not tried to simulate an FMU with inputs, this is something I plan to try in the near future.