Preparing for Cosimulation

Overview

The EDA Simulator Link™ MQ HDL Cosimulation block serves as a bridge between the Simulink® and the HDL simulator domains. The block represents an HDL component model within the Simulink software. Using the block, Simulink software writes (drives) signals to and reads signals from the HDL model under simulation in the ModelSim® simulator. Signal exchange between the two domains occurs at regularly scheduled time steps defined by the Simulink sample time.

As you develop an EDA Simulator Link MQ cosimulation application, you should be familiar with how signal values are handled across the simulation domains with respect to the following cases:

How Simulink Drives Cosimulation Signals

Although you can bind the output ports of an HDL Cosimulation block to any signal in an HDL model hierarchy, you must use some caution when connecting signals to input ports. Ensure that the signal you are binding to does not have other drivers. If it does, use resolved logic types; otherwise you may get unpredictable results.

If you need to use a signal that has multiple drivers and it is resolved (for example, it is of VHDL type STD_LOGIC) , Simulink applies the resolution function at each time step defined by the signal's Simulink sample rate. Depending on the other drivers, the Simulink value may or may not get applied. Furthermore, Simulink has no control over signal changes that occur between its sample times.

Representation of Simulation Time

The representation of simulation time differs significantly between the HDL simulator and Simulink.

In ModelSim SE/PE, the unit of simulation time is referred to as a tick. The duration of a tick is defined by the HDL simulator resolution limit. The default resolution limit is 1 ns.

To determine current ModelSim resolution limit, enter echo $resolution or report simulator state at the ModelSim prompt. You can override the default resolution limit by specifying the -t option on the ModelSim command line, or by selecting a different Simulator Resolution in the ModelSim Simulate dialog box. Available resolutions in ModelSim are 1x, 10x, or 100x in units of fs, ps, ns, us, ms, or sec. See the ModelSim documentation for further information.

Simulink maintains simulation time as a double-precision value scaled to seconds. This representation accommodates modeling of both continuous and discrete systems.

The relationship between Simulink and the HDL simulator timing affects the following aspects of simulation:

During a simulation run, Simulink communicates the current simulation time to the HDL simulator at each intermediate step. (An intermediate step corresponds to a Simulink sample time hit. Upon each intermediate step, new values are applied at input ports, or output ports are modified.) To bring the HDL simulator up-to-date with Simulink during cosimulation, sampled Simulink time must be converted to HDL simulator time (ticks) and the HDL simulator must run for the computed number of ticks.

The EDA Simulator Link MQ cosimulation interface provides controls that let you configure the timing relationship between the HDL simulator and Simulink and avoid timing errors caused by differences in timing representation.

Defining the Simulink and HDL Simulator Timing Relationship

The Timescales pane of the HDL Cosimulation block parameters dialog lets you choose an optimal timing relationship between Simulink and the HDL simulator. The figure below shows the default settings of the Timescales pane.

The Timescales pane defines a correspondence between one second of Simulink time and some quantity of HDL simulator time. This quantity of HDL simulator time can be expressed in one of the following ways:

The following sections discuss these two timing modes.

Relative Timing Mode

Relative timing mode defines the following one-to-one correspondence between simulation time in Simulink and the HDL simulator:

This correspondence holds regardless of the HDL simulator timing resolution.

The following pseudocode shows how Simulink time units are quantized to HDL simulator ticks:

InTicks = N * tInSecs

where InTicks is the HDL simulator time in ticks, tInSecs is the Simulink time in seconds, and N is a scale factor.

Operation of Relative Timing Mode.   By default, the HDL Cosimulation block is configured for relative mode, with a scale factor of 1. Thus, 1 Simulink second corresponds to 1 tick in the HDL simulator. In the default case:

Relative Timing Mode Example.  

To understand how relative timing mode operates, review cosimulation results from the following example model.

The model contains an HDL Cosimulation block (labeled VHDL Cosimulation INVERTER) simulating an 8-bit inverter that is enabled by an explicit clock. The inverter has a single input and a single output. The VHDL code for the inverter is listed below:

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ENTITY inverter IS PORT (
  
  inport : IN  std_logic_vector := "11111111";
  outport: OUT std_logic_vector := "00000000";
  clk:IN  std_logic
);
END inverter;

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;

ARCHITECTURE behavioral OF inverter IS
BEGIN
  PROCESS(clk)
  BEGIN
    IF (clk'EVENT AND clk = '1') THEN
        outport <= NOT inport;
    END IF;
  END PROCESS;
END behavioral;

A cosimulation of this model might have the following settings:

The figure below shows the ModelSim wave window after a cosimulation run of the example Simulink model for 60 ns. The wave window shows that ModelSim simulated for 60 ticks (60 ns). The inputs change at multiples of 24 ns and the outputs are read from ModelSim at multiples of 12 ns. The clock is driven low and high at intervals of 5 ns.

Now consider a cosimulation of the same model, this time configured with a scale factor of 100 in the Timescales pane.

The ModelSim wave window below shows that Simulink port and clock times were scaled by a factor of 100 during simulation. ModelSim simulated for 6 microseconds (60 * 100 ns). The inputs change at multiples of 24 * 100 ns and outputs are read from ModelSim at multiples of 12 * 100 ns. The clock is driven low and high at intervals of 500 ns.

Absolute Timing Mode

Absolute timing mode lets you define the timing relationship between Simulink and the HDL simulator in terms of absolute time units and a scale factor:

To configure the Timescales parameters for absolute timing mode, you select a unit of absolute time, rather than Tick.

In absolute timing mode, all sample times and clock periods in Simulink are quantized to HDL simulator ticks. The following pseudocode illustrates the conversion:

tInTicks = tInSecs * (tScale / tRL)

where:

For example, given a Timescales pane setting of 1 s and an HDL simulator resolution limit of 1 ns, an output port sample time of 12 ns would be converted to ticks as follows:

			tInTicks = 12ns * (1s / 1ns) = 12
 	

Operation of Absolute Timing Mode.   To understand the operation of absolute timing mode, we will again consider the example model discussed in Operation of Relative Timing Mode. Suppose that the model is reconfigured as follows:

Given these simulation parameters, Simulink will cosimulate with the HDL simulator for 60 ns. Inputs are sampled at a intervals of 24 ns and outputs are updated at intervals of 12 ns. Clocks are driven at intervals of 10 ns.

The figure below shows the ModelSim wave window after a cosimulation run.

Timing Mode Usage Restrictions

The following restrictions apply to the use of absolute and relative timing modes:

Setting HDL Cosimulation Port Sample Times

In general, Simulink handles the sample time for the ports of an HDL Cosimulation block as follows:

If you are developing a model for cosimulation in relative timing mode, consider the following sample time guideline:

Handling Multirate Signals

EDA Simulator Link MQ software supports the use of multirate signals, signals that are sampled or updated at different rates, in a single HDL Cosimulation block. An HDL Cosimulation block exchanges data for each signal at the Simulink sample rate for that signal. For input signals, an HDL Cosimulation block accepts and honors all signal rates.

The HDL Cosimulation block also lets you specify an independent sample time for each output port. You must explicitly set the sample time for each output port, or accept the default. This lets you control the rate at which Simulink updates an output port by reading the corresponding signal from the HDL simulator.

Handling Frame-Based Signals

This section discusses how to improve the performance of your cosimulation by using frame-based signals. An example is provided.

Overview

The HDL Cosimulation block supports processing of single-channel frame-based signals.

A frame of data is a collection of sequential samples from a single channel or multiple channels. One frame of a single-channel signal is represented by a M-by-1 column vector. A signal is frame- based if it is propagated through a model one frame at a time.

Frame-based processing requires the Signal Processing Blockset software. Source blocks from the Signal Processing Sources library let you specify a frame-based signal by setting the Samples per frame block parameter. Most other signal processing blocks preserve the frame status of an input signal. You can use the Buffer block to buffer a sequence of samples into frames.

Frame-based processing can improve the computational time of your Simulink models, because multiple samples can be processed at once. Use of frame-based signals also lets you simulate the behavior of frame-based systems more accurately.

See "Working with Signals" in the Signal Processing Blockset documentation for detailed information about frame-based processing.

Using Frame-Based Processing

You do not need to configure the HDL Cosimulation block in any special way for frame-based processing. To use frame-based processing in a cosimulation, connect one or more single-channel frame-based signals to the input port(s) of the HDL Cosimulation block. All such signals must meet the requirements described in Frame-Based Processing Requirements and Restrictions. The HDL Cosimulation block automatically configures its output(s) for frame-based operation at the appropriate frame size.

Note that use of frame-based signals affects only the Simulink side of the cosimulation. The behavior of the HDL code under simulation in the HDL simulator does not change in any way. Simulink assumes that HDL simulator processing is sample-based. Samples acquired from the HDL simulator are assembled into frames as required by Simulink. Conversely, output data framed by Simulink is transmitted to the HDL simulator in frames, which are unpacked and processed by the HDL simulator one sample at a time.

Frame-Based Processing Requirements and Restrictions.   Observe the following restrictions and requirements when connecting frame-based signals in to an HDL Cosimulation block:

Frame-based processing in the Simulink model is transparent to the operation of the HDL model under simulation in the HDL simulator. The HDL model is presumed to be sample-based. The following constraint also applies to the HDL model under simulation in the HDL simulator:

Frame-Based Cosimulation Example

This example shows the use of the HDL Cosimulation block to cosimulate a VHDL implementation of a simple lowpass filter. In the example, you will compare the performance of the simulation using frame-based and sample-based signals.

The example files are:

The example uses the data file matlabroot\toolbox\signal\signal\mtlb.mat as an input signal. This file contains a speech signal. The sample data is of data type double, sampled at a rate of 8 kHz.

The figure below shows the frame_filter_cosim.mdl model.

The Audio Source Signal From Workspace block provides an input signal from the workspace variable mtlb. The block is configured for an 8 kHz sample rate, with a frame size of 80, as shown in this figure.

The sample rate and frame size of the input signal propagate throughout the model.

The VHDL code file lp_fir_8k.vhd implements a simple lowpass FIR filter with a cutoff frequency of 1500 Hz. The HDL Cosimulation block simulates this HDL module. The HDL Cosimulation block ports and clock signal are configured to match the corresponding signals on the VHDL entity.

Note that for the ModelSim simulation to execute correctly, the clk_enable signal of the lp_fir_8k entity must be forced high. The signal is forced by a pre-simulation command transmitted by the HDL Cosimulation block. The command has been entered into the Tcl pane of the HDL Cosimulation block, as shown in the figure below.

Output data from the HDL Cosimulation block is returned the workspace variable audiobuff1 via the Filtered Signal To Workspace block.

To run the cosimulation, perform the following steps:

  1. Start MATLAB and make it your active window.

  2. Set up and change to a writable working directory that is outside the context of your MATLAB installation directory.

  3. Add the demo directory (matlabroot\toolbox\modelsim\modelsimdemos\frame_cosim) to the MATLAB path.

  4. Copy the demo VHDL file lp_fir_8k.vhd to your working directory.

  5. Open the example model.

    open frame_filter_cosim.mdl
    
  6. Load the source speech signal, which will be filtered, into the MATLAB workspace.

     load mtlb
    

    If you have a compatible sound card, you can play back the source signal by typing the following commands at the MATLAB command prompt:

    a = audioplayer(mtlb,8000);
    play(a);
  7. Start ModelSim by typing the following command at the MATLAB command prompt:

    vsim

    The ModelSim window should now be active. If not, start it.

  8. At the ModelSim prompt, create a design library, and compile the VHDL filter code from the source file lp_fir_8k.vhd, by typing the following commands:

    vlib work
    vmap work work
    vcom lp_fir_8k.vhd
    
  9. The lowpass filter to be simulated is defined as the entity lp_fir_8k. At the ModelSim prompt, load the instantiated entity lp_fir_8k for cosimulation:

    vsimulink lp_fir_8k
    

    ModelSim is now set up for cosimulation.

  10. Start MATLAB. Run a simulation and measure elapsed time as follows:

    t = clock; sim(gcs); etime(clock,t)
    
    ans =
    
        2.7190

    The timing above is typical for a run of this model given a simulation Stop time of 1 second and a frame size of 80 samples. Timings are system-dependent and will vary slightly from one simulation run to the next.

    Take note of the timing you obtained. For the next simulation run, you will change the model to sample-based operation and obtain a comparative timing.

  11. The filtered audio signal returned from ModelSim is stored in the workspace variable audiobuff1. If you have a compatible sound card, you can play back the filtered signal to hear the effect of the lowpass filter. Play the signal by typing the following commands at the MATLAB command prompt:

    b = audioplayer(audiobuff1,8000);
    play(b);
  12. Open the block parameters dialog of the Audio Source Signal From Workspace block and set the Samples per frame property to 1, as shown in this figure.

  13. Close the dialog and select the Simulink window. Select Update diagram from the Edit menu.

    The block diagram now indicates that the source signal (and all signals inheriting from it) is a scalar, as shown in the following figure.

  14. Start ModelSim. At the ModelSim prompt, type

    restart
    
  15. Start MATLAB. Run a simulation and measure elapsed time as follows:

    t = clock; sim(gcs); etime(clock,t)
    
    ans =
    
        3.8440

    Observe that the elapsed time has increased significantly with a sample-based input signal. The timing above is typical for a sample-based run of this model given a simulation Stop time of 1 second. Timings are system-dependent and will vary slightly from one simulation run to the next.

  16. Close down the simulation in an orderly way. In ModelSim, stop the simulation by selecting Simulate > End Simulation, and quit ModelSim. Then close the Simulink model window.

Avoiding Race Conditions in HDL Simulation

In ModelSim SE/PE, it is not possible to guarantee the order in which clock signals (rising-edge or falling-edge) defined in the HDL Cosimulation block are applied, relative to the data inputs driven by these clocks. Therefore, if care is not taken to ensure the relationship between the data and active edges of the clock, race conditions could create non-deterministic cosimulation results.

For more on race conditions in hardware simulators, see Race Conditions in HDL Simulators.

Block Simulation Latency

Simulink and the EDA Simulator Link MQ Cosimulation blocks supplement the hardware simulator environment, rather than operate as part of it. During cosimulation, Simulink does not participate in the HDL simulator delta-time iteration. From the Simulink perspective, all signal drives (reads) occur during a single delta-time cycle. For this reason, and due to fundamental differences between the HDL simulator and Simulink with regard to use and treatment of simulation time, some degree of latency is introduced when you use EDA Simulator Link MQ Cosimulation blocks. The latency is a time lag that occurs between when Simulink begins the deposit of a signal and when the effect of the deposit is visible on cosimulation block output.

As the following figure shows, Simulink cosimulation block input affects signal values just after the current HDL simulator time step (t+δ) and block output reflects signal values just before the current HDL simulator step time (t-δ) .

Regardless of whether your HDL code is specified with latency, the cosimulation block has a minimum latency that is equivalent to the cosimulation block's output sample time. For large sample times, the delay can appear to be quite long, but this is an artifact of the cosimulation block, which exchanges data with the HDL simulator at the block's output sample time only. This may be reasonable for a cosimulation block that models a device that operates on a clock edge only, such as a register-based device.

For cosimulation blocks that model combinatorial circuits, you may want to experiment with a faster sample frequency for output ports. For cosimulation blocks that model combinatorial circuits, you may want to experiment with a faster sampling frequency for output ports in order to reduce this latency.runn

Block Latency Example

To visualize cosimulation block latency, consider the following VHDL code and Simulink model. The VHDL code represents an XOR gate:

-- edgedet.vhd

LIBRARY IEEE;
USE IEEE.std_logic_1164.all;
ENTITY edgedet IS
END edgedet;

ARCHITECTURE behavioral OF edgedet IS
SIGNAL a : std_logic;
SIGNAL b : std_logic;
SIGNAL y : std_logic;
BEGIN 
  y <= a XOR b;
END behavioral;

In the Simulink model, the cosimulation block VHDL Edge Detector contains an XOR circuit. The second cosimulation block, VHDL Fast Output, simply reads the same XOR output. The first block is driven by a signal generated by the Pulse Generator block. The Data Type Conversion block converts the signal to a boolean value. The signal is then treated three different ways:

The second cosimulation block, VHDL Fast Output, is a source block that reads the output of the XOR circuit and passes it on to the Scope block for display.

Now, assume that ModelSim is set up with a resolution limit of 100 ns and an iteration limit of 5000, and that the sample times for the blocks in the Simulink model are as follows:

BlockSample TimeValue
Pulse GeneratorSample time100
Data Type Conversion blockSample timeInherited from Pulse Generator block
Unit Delay blockSample timeInherited from Data Type Conversion block
HDL Cosimulation block—Edge DetectorInput sample timeInherited from Unit Delay block
 Output sample time100
HDL Cosimulation block—Fast Output (source)Output sample time100

After the simulation runs, the ModelSim wave window appears as follows.

Note the following:

The following figure highlights the individual signal paths that get appear in the Simulink Scope window.

The signal that bypasses the cosimulation blocks rises at t=1000. That signal stays high for the duration of the sample period. However, the signals that are read from output port y of the two cosimulation blocks, display in the Scope window as follows:

For cosimulation blocks that model combinatorial circuits, such as the one in the preceding example, you may want to experiment with a faster sample frequency for output ports. For example, suppose you change the Output sample time for the VHDL Fast Output cosimulation block from 100 to 20. The following figure highlights the individual signal paths that appear in the Scope window for this scenario.

In this case, the signal that bypasses the cosimulation blocks and the output signal read from the VHDL Edge Detect block remain the same. However, the delay for the signal read from the VHDL Fast Output block is 20 ticks instead of 100. Although the size of the time step is still tied to the ModelSim resolution limit, the delay that occurs before the VHDL code is processed is significantly reduced and the time of execution more closely reflects simulation time in ModelSim.

Interfacing with Continuous Time Signals

Use the Simulink Zero-Order Hold block to apply a zero-order hold (ZOH) on continuous signals that are driven into an HDL Cosimulation block.

Setting Simulink Software Configuration Parameters

When you create a Simulink model that includes one or more EDA Simulator Link MQ Cosimulation blocks, you might want to adjust certain Simulink parameter settings to best meet the needs of HDL modeling. For example, you might want to adjust the value of the Stop time parameter in the Solver pane of the Configuration Parameters dialog box.

You can adjust the parameters individually or you can use the M-file dspstartup, which lets you automate the configuration process so that every new model that you create is preconfigured with the following relevant parameter settings:

ParameterDefault Setting
'SingleTaskRateTransMsg''error'
'Solver''fixedstepdiscrete'
'SolverMode''singletasking'
'StartTime''0.0'
'StopTime''inf'
'FixedStep''auto'
'SaveTime''off'
'SaveOutput''off'
'AlgebraicLoopMsg''error'

The default settings for 'SaveTime' and 'SaveOutput' improve simulation performance.

You can use dspstartup by entering it at the MATLAB command line or by adding it to the Simulink startup.m file. You also have the option of customizing dspstartup settings. For example, you might want to adjust the 'StopTime' to a value that is optimal for your simulations, or set 'SaveTime' to 'on' to record simulation sample times.

For more information on using and customizing dspstartup, see the Signal Processing Blockset documentation. For more information about automating tasks at startup, see the description of the startup command in the MATLAB documentation.

Running and Testing a Hardware Model in Simulink

If you take the approach of designing a Simulink model first, run and test your model thoroughly before replacing or adding hardware model components as EDA Simulator Link MQ Cosimulation blocks.

Simulink and HDL Simulator Communication Options

Select shared memory or socket communication. See Communicating with MATLAB or Simulink and the HDL Simulator.

Starting the HDL Simulator

See Starting the HDL Simulator.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS