Contents

Software and Processor-in-the-Loop (SIL and PIL) Simulation

This example shows how you can use the SIL or PIL simulation mode to verify automatically generated code and collect metrics. With SIL simulation, you can verify the behavior of production-intent source code on your host computer. With PIL simulation, you can verify the compiled object code that you intend to deploy in production; you can run this object code either on real target hardware or on an instruction set simulator. You can compare the SIL or PIL results with a Normal mode simulation and collect metrics including execution time and code coverage.

You should select the approach for SIL or PIL verification that best fits your needs. To help with this choice, consider these questions about your task.

1. For which model component and code interface will you verify the
   generated code?
     a) A top-model (standalone code interface)
     b) A subsystem (right-click build and standalone code
        interface)
     c) A referenced model (model reference code interface)
2. How will you apply input stimulus signals or test vectors to your
   component under test?
     a) Load stimulus data from the MATLAB(R) workspace or from a
        MATLAB(R) script
     b) Use a test harness model (or a system model) to generate
        stimulus data
3. Is it important to rapidly switch between normal, SIL, or PIL
   simulation mode without making changes to your model?
     a) Yes - it must be easy to switch simulation mode simply by
        choosing from a menu selection
     b) No - it is acceptable to change the model and insert a
        special block to represent a component running in SIL or PIL
        mode
4. If you intend to verify object code executing in the target
   environment (real hardware or instruction set simulator), which
   of the following options apply to your situation?
     a) The products from MathWorks(R) support your compiler and
        target environment
     b) There is a third party, off-the-shelf PIL configuration for
        your target environment
     c) You will use the documented API to implement a connectivity
        configuration that supports your target environment

Study the examples below to help you determine the right approach for your situation.

See also rtwdemo_custom_pil_scriptrtwdemo_custom_pil_script, rtwdemo_rtiostream_scriptrtwdemo_rtiostream_script

Example 1: SIL or PIL Block Simulation for Subsystems

This example shows how the automatically generated SIL block can be used for verification. With this approach:

  • You can verify code generated for subsystems or top models (standalone code interface)

  • You must provide a test harness model (or a system model) to supply test vector or stimulus inputs

  • You must swap your original subsystem with an automatically generated SIL block; you should be careful to avoid saving your model in this state as you would lose your original subsystem

Open a simple model by typing the following MATLAB® commands. The model comprises a control algorithm connected in closed loop with a plant model. The control algorithm is designed to regulate the output from the plant.

model='rtwdemo_sil_block';
close_system(model,0)
open_system(model)
out = sim(model,10);
yout_normal = find(out,'yout');
clear out

Configure the build process to create the SIL block for verification. When code is generated for this model - or one of its subsystems - a SIL block is automatically created.

set_param(model,'CreateSILPILBlock','SIL');

Generate code for the control algorithm subsystem by running the commands below. Alternatively, right-click the subsystem and select C/C++ Code > Build This Subsystem. In the dialog box that opens, click Build. The SIL block is created at the end of the build and its input/output ports match those of the control algorithm subsystem.

close_system('untitled',0);
rtwbuild([model '/Controller'])
### Starting build procedure for model: Controller
### Creating SIL block ...
Building with 'gcc'.
MEX completed successfully.
### Successful completion of build procedure for model: Controller

Simulate the model

To perform a SIL simulation, with the controller configured in closed loop with the plant model, you must replace the original control algorithm with the new SIL block. Run the following commands to perform this replacement automatically.

controllerBlock = [model '/Controller'];
blockPosition = get_param(controllerBlock,'Position');
delete_block(controllerBlock);
add_block('untitled/Controller',[controllerBlock '(SIL)'],...
          'Position', blockPosition);
close_system('untitled',0);
clear controllerBlock blockPosition

Run the SIL simulation and plot the results to compare with the normal simulation. Do the normal and SIL simulation results differ? The control algorithm uses single precision floating point arithmetic; you should expect to see differences with order of magnitude in the region of machine precision for single precision data. If you need to verify the exact behaviour on production hardware, you should use PIL simulation.

out = sim(model,10);
yout_sil = find(out,'yout');
tout = find(out,'tout');

% Define an error tolerance based on machine precision for the normal simulation
% result represented in single precision
machine_precision = eps(single(yout_normal));
tolerance = 4 * machine_precision;

fig1 = figure;
subplot(3,1,1), plot(yout_normal), title('Controller output for normal simulation')
subplot(3,1,2), plot(tout, [abs(yout_normal-yout_sil) tolerance]), ...
    title('Error and error tolerance threshold')
subplot(3,1,3), plot(yout_sil), title('Controller output for SIL simulation');
### Preparing to start SIL block simulation: <a href="matlab: targets_hyperlink_manager('run',1);">rtwdemo_sil_block/Controller(SIL)</a> ...
### Starting SIL simulation for component: rtwdemo_sil_block/Controller
### Stopping SIL simulation for component: rtwdemo_sil_block/Controller

Clean up

close_system(model,0);
if ishandle(fig1), close(fig1), end
clear fig1
simResults={'out','yout_sil','yout_normal','tout','machine_precision'};
save([model '_results'],simResults{:});
clear(simResults{:},'simResults')

Example 2: SIL or PIL Simulation for Model Blocks

This example shows how you can verify the automatically generated code for a model by running a SIL simulation using a Model block in a test harness model.

With this approach:

  • You can verify code generated for referenced models (model reference code interface) or top models (standalone code interface)

  • You must provide a test harness model (or a system model) to provide test vector or stimulus inputs

  • You can easily switch a Model block between normal and SIL or PIL simulation mode

  • To run a PIL simulation, you must have a target-specific connectivity configuration available. A connectivity configuration allows the PIL simulation to build the target application, download it to real hardware or an instruction set simulator then, launch the application and communicate with it during the simulation. For details on support for this simulation mode, see the documentation for that product.

Open an example model by typing the following MATLAB® commands. The model contains two Model blocks that both point at the same referenced model. One of the Model blocks is configured to run in SIL simulation mode and the other in normal mode.

model='rtwdemo_sil_modelblock';
open_system(model);

Switch off code coverage

coverageSettings = get_param(model, 'CodeCoverageSettings');
coverageSettings.CoverageTool='None';
set_param(model, 'CodeCoverageSettings',coverageSettings);

Selecting the code under test

The Model block's "Code under test" parameter provides two options:

a) "Top model": Test the model as a top-level deployable component that has the standalone code interface. The code under test is the code that is generated by the slbuild('rtwdemo_sil_counter') command.

b) "Model reference": Test the model as a component within a model reference hierarchy. The code under test is the code that is generated by the slbuild('rtwdemo_sil_counter', 'ModelReferenceRTWTarget') command.

To view the Model block parameters, right-click the Model block and select Block Parameters (ModelReference) or double-click the viewing block. The "Code under test" parameter is only available for SIL and PIL simulation modes.

Simulate the model (top model code under test)

Execute the following commands to run a simulation and plot the results. As one of the model blocks is configured to run in SIL mode with "Top model" code under test, you will see in the Command Window that standalone code is generated for the referenced model (unless generated code already exists from a previous build). Note that the model block running in SIL mode is executed as a separate process on your computer.

set_param([model '/CounterA'], 'CodeUnderTest', 'Top model');
out = sim(model,20);
### Successfully updated the model reference SIM target for model: rtwdemo_sil_counter
### Starting build procedure for model: rtwdemo_sil_counter
### Successful completion of build procedure for model: rtwdemo_sil_counter
### Preparing to start SIL simulation ...
Building with 'gcc'.
MEX completed successfully.
### Updating code generation report with SIL files ...
### Starting SIL simulation for component: rtwdemo_sil_counter
### Stopping SIL simulation for component: rtwdemo_sil_counter

Compare the behavior of Model blocks executing in normal and SIL simulation modes by running the following commands. The behaviors should match exactly.

yout = find(out,'logsOut');
yout_sil = yout.get('counterA').Values.Data;
yout_normal = yout.get('counterB').Values.Data;
fig1 = figure;
subplot(3,1,1), plot(yout_normal), title('Counter output for normal simulation')
subplot(3,1,2), plot(yout_normal-yout_sil), title('Error')
subplot(3,1,3), plot(yout_sil), title('Counter output for Model block SIL (top model) simulation');

Simulate the model (model reference code under test)

Execute the following commands to run a simulation and plot the results. As one of the model blocks is configured to run in SIL mode, you will see in the Command Window that code is generated for the referenced model (unless generated code already exists from a previous build). Note that the model block running in SIL mode is executed as a separate process on your computer.

set_param([model '/CounterA'], 'CodeUnderTest', 'Model reference');
out2 = sim(model,20);
### Starting build procedure for model: rtwdemo_sil_counter
### Successful completion of build procedure for model: rtwdemo_sil_counter
### Preparing to start SIL simulation ...
Building with 'gcc'.
MEX completed successfully.
### Updating code generation report with SIL files ...
### Starting SIL simulation for component: rtwdemo_sil_counter
### Stopping SIL simulation for component: rtwdemo_sil_counter

Compare the behavior of Model blocks executing in normal and SIL simulation modes by running the following commands. The behaviors should match exactly.

yout2 = find(out2,'logsOut');
yout2_sil = yout2.get('counterA').Values.Data;
yout2_normal = yout2.get('counterB').Values.Data;
fig2 = figure;
subplot(3,1,1), plot(yout2_normal), title('Counter output for normal simulation')
subplot(3,1,2), plot(yout2_normal-yout2_sil), title('Error')
subplot(3,1,3), plot(yout2_sil), title('Counter output for Model block SIL (model reference) simulation');

Clean up

close_system(model,0);
if ishandle(fig1), close(fig1), end, clear fig1
if ishandle(fig2), close(fig2), end, clear fig2
simResults={'out','yout','yout_sil','yout_normal', ...
            'out2','yout2','yout2_sil','yout2_normal', ...
            'SilCounterBus','T','reset','ticks_to_count','Increment'};
save([model '_results'],simResults{:});
clear(simResults{:},'simResults')

Example 3: SIL or PIL Simulation for Top Models

This example shows how you can verify the automatically generated code for a top model by running a SIL or PIL simulation. With this approach:

  • You can verify code generated for a top model (standalone code interface)

  • You must configure the model to load test vectors or stimulus inputs from the MATLAB® workspace

  • You can easily switch the entire model between normal and SIL or PIL simulation mode

  • To run a PIL simulation, you must have a target-specific connectivity configuration available. A connectivity configuration allows the PIL simulation to build the target application, download it to real hardware or an instruction set simulator then, launch the application and communicate with it during the simulation. For details on support for this simulation mode, see the documentation for that product.

Open an example model by typing the following MATLAB® commands. The model is a simple counter.

model='rtwdemo_sil_topmodel';
close_system(model,0)
open_system(model)
set_param(gcs, 'RecordCoverage','off')

Configure the input stimulus data

[ticks_to_count, reset, counter_mode, count_enable] = ...
    rtwdemo_sil_topmodel_data(T);

Configure logging options in the model

set_param(model, 'LoadExternalInput','on');
set_param(model, 'ExternalInput','ticks_to_count, reset, counter_mode, count_enable');
set_param(model, 'SignalLogging', 'on');
set_param(model, 'SignalLoggingName', 'logsOut');

Switch on execution profiling and switch off code coverage

set_param(model, 'CodeExecutionProfiling','on');
set_param(model, 'CodeProfilingInstrumentation','on');
set_param(model, 'CodeProfilingSaveOptions','AllData');
coverageSettings = get_param(model, 'CodeCoverageSettings');
coverageSettings.CoverageTool='None';
set_param(model, 'CodeCoverageSettings',coverageSettings);

Simulate the model

Enter the following commands to run first a normal mode, then a SIL simulation and compare the results.

set_param(model,'SimulationMode','normal')
[~, ~, yout_normal] = sim(model,10);

Run a SIL simulation; unless code for this model already exists and is up to date, new code will be generated and compiled. When the simulation runs, this code is executed as a separate process on your host computer.

set_param(model,'SimulationMode','Software-in-the-Loop (SIL)')
[~, ~, yout_sil] = sim(model,10);
### Starting build procedure for model: rtwdemo_sil_topmodel
### Successful completion of build procedure for model: rtwdemo_sil_topmodel
### Preparing to start SIL simulation ...
Building with 'gcc'.
MEX completed successfully.
### Updating code generation report with SIL files ...
### Starting SIL simulation for component: rtwdemo_sil_topmodel
### Stopping SIL simulation for component: rtwdemo_sil_topmodel

Run the following commands to plot and compare the results of normal and SIL simulation. The behaviors should match exactly.

fig1 = figure;
subplot(3,1,1), plot(yout_normal), title('Counter output for normal simulation')
subplot(3,1,2), plot(yout_normal-yout_sil), title('Error')
subplot(3,1,3), plot(yout_sil), title('Counter output for SIL simulation');

Clean up

close_system(model,0);
if ishandle(fig1), close(fig1), end, clear fig1
simResults = {'yout_sil','yout_normal','model','T',...
              'ticks_to_count','reset'};
save([model '_results'],simResults{:}, 'executionProfile');
clear(simResults{:},'simResults')

Execution Time Measurements

In the previous example, you configured the model to collect execution time measurements and saved this data as a variable in the base workspace. The software provides an API to retrieve execution time information from the base workspace variable. For example, you can use the report method to create a summary report.

report(executionProfile);

For more information, see View and Compare Code Execution TimesView and Compare Code Execution Times.

Execution profiling clean up

clear executionProfile

Further Information on Hardware Implementation Settings for SIL Simulation

When you run a SIL simulation, you must configure your hardware implementation settings (i.e. characteristics such as native word sizes) to allow compilation for your host computer. This means that the settings may differ from the hardware implementation settings that you must use when you build the model for your production hardware. You can avoid the need to change hardware implementation settings between SIL and PIL simulation modes by enabling portable word sizes. For further information on this topic see rtwdemo_sil_hardware_configrtwdemo_sil_hardware_config.

Was this topic helpful?