# Documentation

## Common Problems in SimEvents Models

### Unexpectedly Simultaneous Events

An unexpected simultaneity of events can result from roundoff error in event times or other floating-point quantities, and might cause the processing sequence to differ from your expectation about when each event should occur. Computers' use of floating-point arithmetic involves a finite set of numbers with finite precision. Events scheduled on the event calendar for times T and T+Δt are considered simultaneous if 0 ≤ Δt ≤ `128*eps*`T, where `eps` is the floating-point relative accuracy in MATLAB® software and T is the simulation time.

If you have a guess about which events' processing is suspect, adjusting event priorities or using the Instantaneous Event Counting Scope block can help you diagnose the problem. For examples involving event priorities, see Choose Values for Event Priorities. For an example using the Instantaneous Event Counting Scope block, see Count Events from Multiple Sources.

### Unexpectedly Nonsimultaneous Events

An unexpected lack of simultaneity can result from roundoff error in event times or other floating-point quantities. Computers' use of floating-point arithmetic involves a finite set of numbers with finite precision. Events scheduled on the event calendar for times T and T+Δt are considered simultaneous if 0 ≤ Δt ≤ `128*eps*`T, where `eps` is the floating-point relative accuracy in MATLAB software and T is the simulation time.

If roundoff error is very small, the scope blocks might not reveal enough precision to confirm whether events are simultaneous or only close. An alternative technique is to use the Discrete Event Signal to Workspace block to collect data in the MATLAB workspace.

If your model requires that certain events be simultaneous, use modeling techniques aimed at effecting simultaneity. For an example, see Choose Values for Event Priorities.

### Unexpected Processing Sequence for Simultaneous Events

An unexpected sequence for simultaneous events could result from the arbitrary or random handling of events having equal priorities, as described in Processing Sequence for Simultaneous Events. The sequence might even change when you run the simulation again. When the sequence is arbitrary, do not make any assumptions about the sequence or its repeatability.

If you copy and paste blocks that have an event priority parameter, the parameter values do not change unless you manually change them.

An unexpected processing sequence for simultaneous block operations, including signal updates, could result from interleaving of block operations. For information and examples, see Interleaving of Block Operations.

The processing sequence for simultaneous events could have unexpected consequences in the simulation. To learn more about the processing sequence that occurs in your simulation, use the SimEvents® debugger. For tips on using the debugger to examine the processing sequence for simultaneous events, see Explore Simultaneous Events.

To learn which events might be sensitive to priority, try perturbing the model by using different values of blocks' Resolve simultaneous signal updates according to event priority or Event priority parameters. Then run the simulation again and see if the behavior changes.

### Unexpected Use of Old Value of Signal

During a discrete-event simulation, multiple events or signal updates can occur at a fixed value of the simulation clock. If these events and signal updates are not processed in the sequence that you expect, you might notice that a computation or other operation uses a signal value from a previous time instead of from the current time. Some common situations occur when:

If you want notification of some of these situations, use the configuration parameters related to race conditions. For details, see SimEvents Diagnostics Pane.

#### Use a Signal or an Attribute

The goal in the next model (open model) is to use a service time of N seconds for the Nth entity. The Entity Counter block stores each entity's index, N, in an attribute. The top portion of the model uses the attribute directly to specify the service time. The bottom portion creates a signal representing the attribute value and attempts to use the signal to specify the service time. These might appear to be equivalent approaches, but only the top approach satisfies the goal.

The plot of the time in the bottom server block and a warning message in the Command Window both reveal a modeling error in the bottom portion of the model. The first entity's service time is 0, not 1, while the second entity's service time is 1, not 2. The discrepancy between entity index and service time occurs because the Get Attribute block processes the departure of the entity before the update of the signal at the A1 signal output port. That is, the server computes the service time for the newly arrived entity before the A1 signal reflects the index of that same entity. For more information about this phenomenon, see Interleaving of Block Operations.

The top portion of the model, where the server directly uses the attribute of each arriving entity, uses the expected service times. The sequential processing of an entity departure and a signal update does not occur because each entity carries its attributes with it.

 Tip   If your entity possesses an attribute containing a desired service time, switching criterion, timeout interval, or other quantity that a block can obtain from either an attribute or signal, use the attribute directly rather than creating a signal with the attribute's value and having to ensure that the signal is up-to-date when the entity arrives.

### Effect of Initial Value on Signal Loops

When you create a loop in a signal connection, consider the effect of initial values. If you need to specify initial values for event-based signals, see Specify Initial Values of Event-Based Signals.

#### Faulty Logic in Feedback Loop

The following model (open model) generates no entities because the logic is circular. The entity generator is waiting for a change in its input signal, but the server's output signal never changes until an entity arrives or departs at the server.

To use the SimEvents debugger to see that the example has a modeling error:

1. Begin a debugger session for the model. At the MATLAB command prompt, enter:

```simeventsdocex('doc_ic_noentities') sedebug('doc_ic_noentities')```
2. Run the entire simulation. At the `sedebug>>` prompt, enter:

`runtoend`

If the simulation generated entities, the debugger would display messages in the Command Window to indicate that. The lack of output in this case shows that the simulation generates no entities.

A better model (open model) provides the first entity in a separate path. In the revised model, the Time-Based Entity Generator block generates exactly one entity during the simulation, at T=0.

You can use the debugger again to confirm that the revised model generates entities. If you use the preceding procedure, but substitute `'doc_ic_no_entities_fix'` in place of `'doc_ic_no_entities'`, you can see that the debugger reports entity generations and other operations during the simulation of the revised model.

### Loops in Entity Paths Without Sufficient Storage Capacity

An entity path that forms a loop should contain storage that will not become exhausted during the simulation. Storage blocks include queues and servers; for a list of storage blocks, see Storage and Nonstorage Blocks. The following example illustrates how the storage block can prevent a deadlock.

#### Deadlock Resulting from Loop in Entity Path

The following model (open model) contains a loop in the entity path from the Output Switch block to the Path Combiner block. The problem occurs when the switch selects the entity output port OUT2. The entity attempting to depart from the server looks for a subsequent storage block where it can reside. It cannot reside in a routing block. Until the entity confirms that it can advance to a storage block or an entity-destroying block, the entity cannot depart. However, until it departs, the server is not available to accept a new arrival. The result is a deadlock.

To use the SimEvents debugger to identify the deadlock:

1. Begin a debugger session for the model. At the MATLAB command prompt, enter:

```simeventsdocex('doc_loop') sedebug('doc_loop')```
2. Run the simulation until the built-in breakpoint at the end of the simulation. At the `sedebug>>` prompt, enter:

`cont`

The debugger displays log messages in the Command Window so you can see what happens in the simulation. The latest time stamp in the messages is at T = 3:

```%==============================================================================% Executing EntityGeneration Event (ev13) Time = 3.000000000000000 : Entity = <none> Priority = 300 : Block = Time-Based Entity Generator %..........................................................................% Generating Entity (en4) : Block = Time-Based Entity Generator Hit built-in breakpoint for the end of simulation.```

The lack of log messages after T = 3 reflects the deadlock.

3. If you inspect the final state of the switch, you see that it selects the entity output port OUT2:

`blkinfo('doc_loop/Output Switch')`

The output is:

```OutputSwitch Current State T = 10.000000000000000 Block (blk2): Output Switch Advancing Entity = <none> Selected Output Port = 2```
4. If you inspect the final state of the server, you see that it is holding an entity that completed its service at T=2:

`blkinfo('doc_loop/Single Server')`

The output is:

```SingleServer Current State T = 10.000000000000000 Block (blk6): Single Server Entities (Capacity = 1): Pos ID Status Event EventTime 1 en2 Service Completed ev11 2```
5. End the debugger session. At the `sedebug>>` prompt, enter:

`sedb.quit`

A better model (open model) includes a server with a service time of 0 in the looped entity path. This storage block provides a place for an entity to reside after it departs from the Output Switch block. After the service completion event is processed, the entity advances to the Path Combiner block and back to the Single Server block. The looped entity path connects to the Path Combiner block's IN1 entity input port, not IN2. This ensures that entities on the looped path, not new entities from the queue, arrive back at the Single Server block.

### Unexpected Timing of Random Signal

When you use the Event-Based Random Number block to produce a random event-based signal, the block infers from a subsequent block the events upon which to generate a new random number from the distribution. The sequence of times at which the block generates a new random number depends on the port to which the block is connected and on events occurring in the simulation. To learn how to use this block, see Generate Random Signals.

#### Invalid Connection of Event-Based Random Number Generator

The following model (open model) is incorrect because the Event-Based Random Number block cannot infer from the p input port of an Output Switch block when to generate a new random number. The Output Switch block is designed to listen for changes in its p input signal and respond when a change occurs. The Output Switch cannot cause changes in the input signal value or tell the random number generator when to generate a new random number. The p input port of the Output Switch block is called a reactive port and it is not valid to connect a reactive signal input port to the Event-Based Random Number block.

If you want to generate a new random number corresponding to each entity that arrives at the switch, a better model (open model) connects the Event-Based Random Number block to a Set Attribute block and sets the Output Switch block's Switching criterion parameter to `From attribute`. The random number generator then generates a new random number upon each entity arrival at the Set Attribute block. The connection of the Event-Based Random Number block to the A1 input port of the Set Attribute block is a supported connection because the A2 port is a notifying port. To learn more about reactive ports and notifying ports, see the reference page for the Event-Based Random Number block.

### Unexpected Correlation of Random Processes

An unexpected correlation between random processes can result from nonunique initial seeds in different dialog boxes. If you copy and paste blocks that have an Initial seed or Seed parameter, the parameter values do not change unless you manually change them. Such blocks include:

• Time-Based Entity Generator

• Event-Based Random Number

• Entity Splitter

• Blocks in the Routing library

• Uniform Random Number

• Random Number

• Masked subsystems that include any of the preceding blocks

#### Detect Nonunique Seeds and Making Them Unique

To detect and correct some nonunique initial seeds, use a diagnostic setting:

1. Open the Configuration Parameters dialog box for the model using Simulation > Model Configuration Parameters.

2. Navigate to the SimEvents Diagnostics pane of the dialog box.

3. Set Identical seeds for random number generators to `warning`.

When you run the simulation, the application checks for nonunique Initial seed parameter values in SimEvents library blocks. Upon detecting any, the application issues a warning message that includes instructions for solving the problem.

 Exceptions   You must monitor seed values manually if your model contains random-number-generating blocks that come from libraries other than the SimEvents libraries.To learn how to query and change seed values of such blocks, use the techniques illustrated in Work with Seeds Not in SimEvents Blocks.

### Blocks that Require Event-Based Signal Input

If a SimEvents model contains a block that operates directly on an event-based signal, that block must be part of an event execution for it to update its output. Modify the model if the block cannot update its output during a simulation. An example block is an Atomic Subsystem block that does not have any input.

For such blocks to update their outputs during simulation, connect block input ports to event-based signals.

### Invalid Connections of Gateway Blocks

When you select the configuration parameter Prevent duplicate events on multiport blocks and branched signals in your model, the software prohibits some connection types to other discrete-event blocks for the following gateway blocks:

• Timed to Event Signal

• Event to Timed Function-Call

• Timed to Event Function-Call

#### Invalid Connections of Timed to Event Signal Block

In the following model, the value of the Generate Entities Upon: parameter of the Event-Based Entity Generator block is set to ```Sample time hit from port ts```. You cannot connect a time-based signal via a gateway block to a discrete-event block configured to sense sample time hits at its input port. If you run a model containing this type of connection, you see an error in the MATLAB command window.

The software does not allow the type of connection shown in this model because of a difference between the behavior you might expect when the simulation executes this configuration, and the actual simulation behavior when you also select the configuration parameter Prevent duplicate events on multiport blocks and branched signals. Because of this discrepancy, the simulation is likely to generate events at times that you do not intend.

For more information, see Prevent duplicate events on multiport blocks and branched signals.

In this model, you might expect the Event-Based Entity Generator block to sense sample time hits based on the sample rate of the Repeating Sequence Stair block and to generate entities based on those sample time hits. However, if the discrete-event system in the example is contained within a Simulink® model, the software ensures that the entire discrete-event system—including any time-based signals fed into the discrete-event system via gateways—executes at the base rate of the Simulink model. As a result of this execution behavior, the Event-Based Entity Generator block senses sample time hits based on the execution rate of the Simulink model, not based on the sample rate of the incoming time-based signal.

The software enforces the behavior that all blocks of a discrete-event system contained in a Simulink model execute at the base rate of the Simulink model to ensure consistency between the two solver execution modes supported by discrete-event systems: single-tasking mode and multitasking mode.

Starting in SimEvents version 4.0 (R2012a), there is support for fixed-step solvers with discrete-event systems. Therefore, multitasking mode is now an available option for SimEvents® models.

In multitasking mode, the software executes tasks based on a priority it assigns to blocks in the model. The higher the sample rate of a block, the higher the priority the simulation assigns to it. In multitasking mode, without any enforcement of sample rates by the software, it might be possible for multiple gateway blocks to execute at different rates based on the sample rates of the signals connected to them. However, it is inadvisable to allow the simulation to read gateway blocks at rates that are slower than the base rate of the model. Serious data transfer problems might arise between tasks executing at different rates. In a discrete-event system, this behavior might lead to unpredictable production of events and values.

When a discrete-event system is contained in a Simulink model, the software constrains any time-based signal connected to the discrete-event system via a gateway block to be sampled at the base rate of the Simulink model. If you connect a time-based signal via a gateway block to a discrete-event block configured to sense sample time hits at its input port, you see an error in the MATLAB command window.

#### Invalid Connections of Event to Timed Function-Call Block

In the following model, the connection of the Event to Timed Function-Call gateway block is invalid. In this configuration, the gateway block accepts the Out1 signal of the Atomic Subsystem block as an input. The role of the Event to Timed Function-Call gateway block in a model is to convert an incoming event-based function-call signal to a time-based signal. However, in this model, the Out1 signal of the Atomic Subsystem block is already a time-based signal. The Event to Timed Function-Call gateway block performs no useful role.

Connect the input port of the Event to Timed Function-Call gateway block to only the following blocks:

• Signal-Based Function-Call Generator

• Time-Based Function-Call Generator

• Entity Departure Function-Call Generator with value of Timing of function call f1: or Timing of function call f2: parameter set to ```After entity departure```.

#### Invalid Connections of Timed to Event Function-Call Block

In the following model fragment, the output port of the Timed to Event Function-Call gateway block connects to a Function-Call Subsystem block from the Simulink block library. You can connect the output port of the Timed to Event Function-Call gateway block to only a block from the SimEvents library that accepts function-call input signals.

Connect the output port of the Timed to Event Function-Call gateway block to the function-call input port of only these blocks:

• Event-Based Entity Generator

• Release Gate

• Instantaneous Event Counting Scope

• Entity Departure Counter with value of Reset counter upon: parameter set to ```Function call from port fcn```

• Signal-Based Function-Call Generator with value of Function-call delay from: parameter set to `Signal port t` or `Dialog`. If set to `Dialog`, enter a value greater than `0` for the Function-call time delay parameter

### Race Conditions Involving Entity Departure Function Calls

The following model shows a connection of the Entity Departure Function-Call Generator block that, by default, causes an error in your simulation. In this modeling scenario, a race condition exists between the Entity Departure Function-Call Generator block and the Add block.

The Timing of function call f1 parameter of the Entity Departure Function-Call Generator block is set to `Before entity departure`. Before an entity departs the generator block, the block produces a function call that causes the Add block to execute. When the Add block executes, it uses a value of the #d output of the generator block that is still awaiting update. This behavior might cause the Add block to produce an unexpected result.

If you do not require the `Before entity departure` behavior you can resolve this type of race condition shown by changing the value of the Timing of function call f1 parameter of the block to `After entity departure`. If you require the `Before entity departure` behavior and have assessed the impact this race condition might have on your simulation results, you can disable the error that this race condition causes in your simulation. In the dialog box of the Entity Departure Function-Call Generator block, change the value of the Use of signals awaiting update during function call parameter from `error` to `none`.

The following model shows another type of connection using the Entity Departure Function-Call Generator block that by default, causes an error in your simulation. In this case, a race condition exists between both Entity Departure Function-Call Generator blocks.

The Timing of function call f1 parameter of both generator blocks is set to `Before entity departure`. This setting causes a race condition because the function-call output of each block updates the inputs of the same block, the Function-Call Subsystem1 block. If you use multiple ```Before entity departure``` function calls to update inputs of the same block, it is difficult to control which signal values are up to date when the simulation executes that block.

To resolve this race condition, if possible, set the Timing of function call f1 parameter of both generator blocks to `After entity departure`. Or, disable the race condition error by changing the value of the Use of signals awaiting update during function call parameter from `error` to `none`.

### Saving Models at Earlier Versions of SimEvents

Be aware that the following action cannot be reversed. If you use the `Save as type:` drop-down list to save your model at a version of SimEvents prior to 4.0 (R2011b), the software replaces unsupported blocks with empty subsystem blocks. The empty subsystem blocks are marked with the text Replaced. If you save your model in this way, the converted model is likely to generate incorrect results. To restore the functionality of your model, in the model editor, replace empty subsystem blocks with appropriate blocks from the version of SimEvents installed on your computer. When you have finished replacing blocks in your model, verify that all blocks are connected as you intend. Save the model to match the version of SimEvents installed on your computer.

### Blocks That Reference Simulation Time

If your discrete-event system is contained within a Simulink model that uses a fixed-step solver, the discrete-event system cannot contain the following Simulink blocks that reference the current simulation time.

• Digital Clock

• Discrete-Time Integrator

A fixed-step solver processes events in the discrete-event system only at its major time steps. Therefore, for the listed blocks, the simulation does not accurately report the times at which events occur. If you run a model that uses a fixed-step solver and that contains one of the listed blocks, you see an error. To work around the issue, if possible, in the Solver options pane of the Configuration Parameters dialog box, change the value of the Type parameter to `Variable-step`.

### SimEvents Incompatibility with Simulink Simulation Stepper

Simulink provides a tool, the Simulation Stepper, to step through a model simulation.

You can:

• Start and stop model simulation

• Step forward and backward through a model simulation (by default, stepping backward is disabled)

• Add conditional breakpoints to a signal

However, if your model contains SimEvents blocks, you cannot use the Simulink Simulation Stepper to step backward through your model simulation. In the Simulation Stepper, the step back capability relies on SimState (Save and Restore Simulation State as SimState) technology to save and restore the state of a simulation. SimEvents does not support SimState. When you step forward through a model that contains SimEvents blocks, you see a warning. You cannot enable the step back capability.
To step through a model containing SimEvents blocks, instead use the SimEvents Debugger. See Start the SimEvents Debugger.