Mathworks SIMEVENTS 3 user guide

SimEvents
®
User’s Guide
3
How to Contact The MathWorks
www.mathworks. comp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html Technical Support
suggest@mathworks.com Product enhancement suggestions
bugs@mathwo doc@mathworks.com Documentation error reports service@mathworks.com Order status, license renewals, passcodes
info@mathwo
com
rks.com
rks.com
Web
Bug reports
Sales, prici
ng, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
®
SimEvents
© COPYRIGHT 2005–20 10 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
User’s Guide
Revision History
November 2005 Online only New for Version 1.0 (Release 14SP3+) March 2006 Online only Revised for Version 1.1 (Release 2006a) September 2006 O nline only Revised for Version 1.2 (Release 2006b) March 2007 Online only Revised for Version 2.0 (Release 2007a) September 2007 O nline only Revised for Version 2.1 (Release 2007b) March 2008 Online only Revised for Version 2.2 (Release 2008a) October 2008 Online only Revised for Version 2.3 (Release 2008b) March 2009 Online only Revised for Version 2.4 (Release 2009a) September 2009 O nline only Revised for Version 3.0 (Release 2009b) March 2010 Online only Revised for Version 3.1 (Release 2010a)
Working with Entities
1
Generating Entities When Events Occur ............. 1-2
Overview Sample Use Cases for Event-Based Generation of
Entities
........................................ 1-2
....................................... 1-2
Contents
Specifying Generation Times for Entities
Overview Procedure for Generating En titie s at Specified Times
Setting Attributes of Entities
Role of Attributes in SimEvents Models Blocks That Set Attributes Attribute Value Support Example: Setting Attributes
Manipulating Attributes of Entities
Writing Functions to Manipulate Attributes Using Block Diagrams to Manipulate Attributes
Accessing Attributes of Entities
Counting Entities
Counting Departures Across the Simulation Counting Departures per Time Instant Resetting a Counter Upon an Event Associating Each Entity with Its Index
........................................ 1-5
....................... 1-7
.......................... 1-8
............................ 1-9
........................ 1-10
..................... 1-18
.................................. 1-20
.................. 1-22
............ 1-5
............... 1-7
................. 1-13
............ 1-13
............ 1-20
................ 1-20
................ 1-24
.... 1-5
........ 1-15
Combining Entities
Overview of the Entity-Combining Operation Example: Waiting to Combine Entities Example: Copying Timers When Combining Entities Example: Managing Data in Composite Entities
................................ 1-25
................ 1-25
........... 1-25
.... 1-27
........ 1-28
v
Replicating Entities on Multiple Paths .............. 1-33
Sample Use Cases Modeling Notes
................................. 1-33
................................... 1-33
Working with Events
2
Supported Events in SimEvents Models ............. 2-2
Types of Supported Events Signal-Based Events Function Calls
Example: Event Calendar Usage for a Queue-Server
Model
Overview o f Example Start of Simulation Generation of First Entity Generation of Second Entity Completion of Service Time Generation of Third Entity Generation of Fourth Entity Completion of Service Time
.......................................... 2-10
.................................... 2-8
................................ 2-11
.......................... 2-2
............................... 2-4
.............................. 2-10
.......................... 2-11
......................... 2-12
......................... 2-13
.......................... 2-14
......................... 2-15
......................... 2-16
vi Contents
Observing Events
Techniques for Observing Events Example: Observing Service Completions Example: Detecting Collisions by Comparing Events
Generating Function -Call Events
Role of Explicitly Generated Events Generating Events When Other Events Occur Generating Events Using Intergene ration Times
Manipulating Events
Reasons to Manipulate Events Blocks for Manipulating Events Creating a Union of Multiple Events Translating Events to Control the Processing Se qu e nce Conditionalizing Events
.................................. 2-18
..................... 2-18
.............. 2-22
................... 2-28
.................. 2-28
.......... 2-28
............................... 2-32
....................... 2-32
...................... 2-34
.................. 2-34
............................ 2-39
.... 2-25
........ 2-30
.. 2-37
Managing Simultaneous Events
3
Overview of Simultaneous Events ................... 3-2
Exploring Simultaneous Events
Using Nearby Breakpoints to Focus on a Particular
Time
.......................................... 3-5
For Further Information
Choosing an Approach for Simultaneous Events
Assigning Event Priorities
Procedure for Assigning Event Priorities Tips for Choosing Event Priority Values Procedure for Specifying Equal-Priority Behavior
Example: Choices of Values for Event Priorities
Overview o f Example Arbitrary R esolution of Signal Updates Selecting a Port First Generating Entities First Randomly Selecting a Sequence
Example: Effects of Specifying Event Priorities
Overview of the Example Default Behavior Deferring Gate Events Deferring Subsystem Execution to the Event Calendar
.................................. 3-27
............................ 3-5
.............................. 3-11
.............................. 3-12
........................... 3-19
........................... 3-26
............................. 3-28
..................... 3-4
.......................... 3-8
.............. 3-8
............... 3-8
................ 3-12
...................... 3-24
...... 3-7
....... 3-9
...... 3-11
...... 3-26
... 3-30
Working with Signals
4
Role of Event-Based Signals in SimEvents Models .... 4-2
Overview o f Event-Based Signals Comparison with Time-Based Signals
.................... 4-2
................. 4-2
vii
Generating Random Signals ........................ 4-4
Generating Random Event-Based Signals Examples of Random Event-Based Signals Generating Random Time-Based Signals
............. 4-4
............. 4-5
.............. 4-6
Using Data Sets to Create Event-Based Signals
Behavior of the Event-Based Sequence Block Generating Sequences Based on Arbitrary Events
Manipulating Signals
Specifying Initial Values of Event-Based Signals Example: Resampling a Signal Based on Events
SendingDatatotheMATLABWorkspace
Behavior of the Discrete Event Signal to Workspace
Block Example: Sending Queue Length to the Workspace Using the To Workspace Block with Event-Based
Signals
Working w ith Multivalued Signals
Zero-Duration Values of Signals Importance of Zero-Duration Values Detecting Zero-Duration Values
......................................... 4-15
........................................ 4-18
.............................. 4-12
.................. 4-19
..................... 4-19
.................. 4-20
...................... 4-20
........... 4-9
............ 4-15
....... 4-9
....... 4-10
........ 4-12
........ 4-13
...... 4-15
viii Contents
Modeling Q ueues and Servers
5
Using a LIFO Q ueuing Discipline ................... 5-2
Overview o f LIFO Queues Example: Wa iti n g Time in LIFO Queue
Sorting by Priority
Behavior of the Priority Queue Block Example: FIFO and LIFO as Special Cases of a Priority
Queue Example: Serving Preferred Customers First
......................................... 5-5
................................ 5-5
.......................... 5-2
............... 5-2
................. 5-5
........... 5-8
Preempting an Entity in a Server ................... 5-11
Definition of Preemption Criteria fo r Preemption Residual Service Time Queuing D isciplines for Preemptive Servers Example: Preemption by High-Priority Entities
............................ 5-11
............................ 5-11
............................. 5-12
............ 5-12
......... 5-12
Determining Whether a Queue Is Nonempty
Modeling Multiple Servers
Blocks that Model Multiple Servers Example: M/M/5 Queuing System
Modeling the Failure of a Server
Server States Using a Gate to Implement a Failure State Using Stateflow Charts to Implement a Failure State
..................................... 5-20
......................... 5-18
................... 5-18
.................... 5-18
.................... 5-20
......... 5-17
............ 5-20
Routing Techniques
6
Output Switching Based on a Signal ................. 6-2
Specifying an Initial Port Selection Using the Storage Option to Prevent Latency Problems
Example: Cascaded Switches with Skewed
Distribution
..................................... 6-6
................... 6-2
.... 5-21
.. 6-2
Example: Compound Switching Logic
............... 6-7
Using Logic
7
Role of Logic in SimEvents Models .................. 7-2
ix
Using Embedded MATLAB Functio n Blocks for
Logic
Overview of Use of Embedded MATLAB Function
Example: Choosing the Shortest Queue Example: Varying Fluid Flow Rate Based on Batchi ng
........................................... 7-3
Blocks
........................................ 7-3
............... 7-3
Logic
.......................................... 7-6
Using Logic Blocks
Overview o f Use of Logic Blocks Example: Using Servers in Shifts Example: Choosing the Shortest Queue Using Logic
Blocks For Further Examples
........................................ 7-14
................................ 7-10
...................... 7-10
.................... 7-11
............................. 7-15
Regulating Arrivals Using Gates
8
Role of Gates in SimEvents Models .................. 8-2
Overview o f Gate Behavior Types of Gate Blocks
Keeping a Gate Open Over a Time Interval
Behavior of Enabled Gate Block Example: Controlling Joint Availability of Two Servers
Opening a Gate Instantaneously
Behavior of Release Gate Block Example: Synchronizing Service Start Times with the
Clock Example: Opening a Gate Upon Entity Departures
......................................... 8-6
.......................... 8-2
............................... 8-3
.......... 8-4
...................... 8-4
.................... 8-6
...................... 8-6
...... 8-7
.. 8-4
x Contents
Combining Gates
Effect of Combining Gates Example: First Entity as a Special Case
.................................. 8-9
.......................... 8-9
............... 8-11
Forcing Departures Using Timeouts
9
Role of Timeouts in SimEvents Models .............. 9-2
Basic Example Using Timeouts
Basic Procedure for Using Timeouts
Schematic Illustrating Procedure Step 1: Designate the Entity Path Step 2: Specify the Timeout Interval Step 3: Specify D estinations for Timed-Out Entities
Defining E ntity Paths on Which Timeouts Apply
Linear Path for Timeouts Branched Path for Timeouts Feedback Path for Timeouts
Handling Entities That Time Out
Common Requirements for Handling Timed-Out
Entities Techniques for Handling Timed-Out Entities Example: Dropped and Timed-Out Packets Example: Rerouting Timed-Out Entities to Expedite
Handling
Example: Limiting the Time Until Service
Completion
....................................... 9-10
...................................... 9-12
..................................... 9-14
........................... 9-7
..................... 9-3
................ 9-4
.................... 9-4
.................... 9-5
.................. 9-5
........................ 9-8
......................... 9-8
................... 9-10
........... 9-10
............ 9-11
..... 9-6
..... 9-7
10
Controlling Timing with Subsystems
Timing Issues in SimEvents Models ................. 10-2
Overview o f Timing Issues Timing for the End of the Simulation Timing for a Statistical Computation TimingforChoosingaPortUsingaSequence
.......................... 10-2
................. 10-2
................. 10-3
.......... 10-4
xi
Role of Discrete Event Subsystems in SimEvents
Models
Overview o f Discrete Event Subsystems Purpose of Discrete Event Subsystems Processing Sequence for Events in Discrete E vent
Subsystems
......................................... 10-7
............... 10-7
................ 10-8
.................................... 10-8
Blocks Inside Discrete Event Subsystems
Working with Discrete Event Subsystem Blocks
Setting Up Signal-Based Discrete Event Subsystems Signal-Based Events That Control Discrete Event
Subsystems
Examples Using Discrete Event Subsystem B locks
Example: Comparing the Lengths of Two Queues Example: Normalizing a Statistic to U se for Routing Example: Ending the Simulation Upon an Event Example: Sending Unrepeated Data to the MATLAB
Workspace Example: Focusing on Events, Not Values Example: Detecting Changes from Empty to Nonempty Example: Logging Data About the First Entity on a
Path
.......................................... 10-25
Creating Entity-Departure Subsystems
Overview of Entity-Departure Subsystems Accessing Blocks for Entity-Departure Subsystems Setting Up Entity-Departure Subsystems
.................................... 10-14
..................................... 10-22
............ 10-10
....... 10-18
........ 10-21
............. 10-23
.............. 10-27
............. 10-27
.............. 10-29
...... 10-11
.... 10-11
.... 10-18
.... 10-19
.. 10-24
...... 10-28
xii Contents
Examples Using Entity-Departure Subsystems
Example: Using Entity-Based Timing for Choosing a
Port
.......................................... 10-30
Example: Performing a Computation on Selected Entity
Paths
Using Function-Call Subsystems
Using Function-Call Subsystems in Discrete-Event
Simulations Use Cases for Function-Call Subsystems
......................................... 10-31
.................... 10-33
.................................... 10-33
.............. 10-33
....... 10-30
11
Setting Up Function-Call Subsystems in SimEvents
Models
........................................ 10-34
Plotting Data
Choosing and Configuring Plotting Blocks ........... 11-2
Sources of Data for Plotting Inserting and Connecting Scope B locks Connections Among Points in Plots Varying Axis Limits Automatically Caching Data in Scopes Examples Using Scope Blocks
......................... 11-2
................ 11-3
................... 11-4
................... 11-5
............................ 11-6
....................... 11-6
Working with Scope Plots
Customizing Plots Exporting Plots
Using Plots for Troubleshooting
Example: Plotting Entity Departures to Verify
Timing
Overview o f Example Model Exhibiting Correct Timing Model Exhibiting Latency
Example: Plotting Event Counts to Check for
Simultaneity
Comparison with Time-Based Plotting Tools
......................................... 11-11
................................. 11-8
................................... 11-9
.................................... 11-15
.......................... 11-8
.................... 11-10
.............................. 11-11
..................... 11-11
........................... 11-13
......... 11-17
xiii
12
Using Statistics
Role of Statistics in Discrete-Event Simulation ....... 12-2
Overview Statistics for Data Analysis Statistics for Run-Time Control
........................................ 12-2
......................... 12-2
...................... 12-3
Accessing Statistics from SimEvents Blocks
Statistics-Related P arameters in Block Dialog Boxes Accessing Statistics Throughout the Simulation Accessing Statistics When Stopping or Pausing
Simulation
Deriving Custom Statistics
Overview o f Approaches to Custom Statistics Graphical Block-Diagram Approach Coded Approach Post-Simulation Analysis Example: Fraction of Dropped Messages Example: Computing a Time Average of a Signal Example: Resetting an Average Periodically
Using Timers
Overview o f Timers Basic Example Using Timer Blocks Basic Procedure for Using Timer Blocks Timing Multiple Entity Paths with One Timer Restarting a Timer from Zero Timing Multiple Processes Independently
..................................... 12-7
......................... 12-8
.................. 12-8
.................................. 12-9
........................... 12-9
.............. 12-9
...................................... 12-20
................................ 12-20
................... 12-21
............... 12-22
........................ 12-24
............. 12-26
.......... 12-5
.... 12-5
........ 12-6
........... 12-8
....... 12-11
........... 12-13
.......... 12-23
xiv Contents
Varying Simulation Results by Managing Seeds
Connection Between Random Numbers and Seeds Making Results Repeatable by Storing Sets of Seeds Setting Seed Values Programmatically Sharing Seeds Among Models WorkingwithSeedsNotinSimEventsBlocks Choosing Seed Values
Regulating the Simulation Length
Overview
........................................ 12-35
.............................. 12-34
....................... 12-30
................ 12-30
.......... 12-31
.................. 12-35
...... 12-28
....... 12-28
..... 12-29
13
Setting a Fixed Stop Time .......................... 12-35
Stopping Upon Processing a Fixed Numbe r of Entities Stopping Upon Reaching a P articular State
............ 12-37
... 12-36
Using Stateflow Charts in SimEvents Models
Role of Stateflow Charts in SimEvents Models ....... 13-2
Guidelines for Using Stateflow and SimEvents
Blocks
Examples Using Stateflow Charts and SimEvents
Blocks
Failure State of Server Go-Back-N ARQ Model
.......................................... 13-3
.......................................... 13-4
............................. 13-4
............................. 13-4
14
Debugging Discrete-Event Simulations
Overview of Debu gg ing Resources .................. 14-2
Overview of the SimEvents Debugger
Starting th e SimEvents Debugger
The Debugger Environment
Debugger Command Prompt Simulation Log in the Debugger Identifiers in the Debugger
Independent Operations and Consequences in the
Debugger
Significance of Independent Operations
....................................... 14-20
........................ 14-7
........................ 14-7
..................... 14-8
......................... 14-18
............... 14-3
................... 14-5
............... 14-20
xv
Independent Operations ............................ 14-20
Consequences of Independent Operations
.............. 14-21
Stopping the Debugger
HowtoEndtheDebuggerSession Comparison of Simulation Control Functions
Stepping Through the Simulation
Overview o f Stepping How to Step Choosing the Granularity of a Step Tips for Stepping Through the Simulation
Inspecting the Current Point in the Debugger
Viewing the Current Operation Obtaining Information Associated with the Current
Operation
Inspecting Entities, Blocks, and Events
Inspecting Entities Inspecting Blocks Inspecting Events Obtaining Identifiers of Entities, Blocks, and Events
Working with Debugging Information in Variables
Comparison of Variables with Inspection Displays Functions That Return Debugging Information in
Variables
How to Create Variables Using State Inspection
Functions Tips for Manipulating Structures and Cell Arrays Example: Finding the Number of Entities in Busy
Servers
...................................... 14-27
...................................... 14-32
...................................... 14-41
...................................... 14-42
........................................ 14-43
............................. 14-24
.................... 14-24
........... 14-24
................... 14-26
.............................. 14-26
................... 14-28
............. 14-29
........ 14-31
...................... 14-31
.............. 14-34
................................ 14-34
................................. 14-36
................................. 14-38
....... 14-41
....... 14-43
.... 14-38
... 14-41
xvi Contents
Viewing the Event Calendar
For Further Information
Customizing the Debugger Simulation Log
Customizable Information in the Simulation Log Tips for Choosing Appropriate Detail Settings Effect of Detail Settings on Stepping
........................ 14-46
............................ 14-46
.................. 14-49
........... 14-47
........ 14-47
.......... 14-48
HowtoViewCurrentDetail Settings ................. 14-51
How to Change Detail Settings HowtoSaveandRestoreDetailSettings
...................... 14-52
.............. 14-53
Debugger Efficiency Tips
Executing Commands Automatically When the D ebugger
Starts
Creating Shortcuts for Debugger Commands
DefiningaBreakpoint
What Is a Breakpoint? Identifying a Point of Interest Setting a Breakpoint Viewing All Breakpoints
Using Breakpoints During Debugging
Running the Simulation Until the Next Breakpoint Ignoring or Removing Breakpoints Enabling a Disabled Breakpoint
Block Operations Relevant for Block Breakpoints
Common Problems in Sim Events Models
Unexpectedly Simultane ous Events Unexpectedly N onsimultaneous Events Unexpected Processing Sequence for Simultaneous
Events
Time-Based Block Not Recognizing Certain Trigger
Edges Incorrect Timing of Signals Unexpected U se of Old Value of Signal Effect of Initial Condition on Signal Loops Loops in Entity Paths Without Sufficient Storage
Capacity Unexpected Timing of Random Signal Unexpected Co rrelation of Random Processes
......................................... 14-54
........................................ 14-73
......................................... 14-74
....................................... 14-83
........................... 14-54
........... 14-55
............................. 14-56
............................. 14-56
....................... 14-56
............................... 14-58
............................ 14-60
............... 14-62
................... 14-63
..................... 14-64
............. 14-72
................... 14-72
............... 14-73
......................... 14-74
................ 14-76
............. 14-80
................. 14-86
.......... 14-88
..... 14-62
.... 14-65
Recognizing Latency in Signal Updates
.............. 14-90
xvii
15
Running Discrete-Event Simulations
Programmatically
Accelerating Discrete-Event Simulations Using Rapid
Simulation
Objective Prerequisites Procedure See Also
...................................... 15-3
........................................ 15-3
..................................... 15-3
........................................ 15-3
......................................... 15-4
Sharing Executables for Discrete-Event Simulations
Objective Model Designer and Model User Roles Procedure for Model Designer Procedure for Model User
Prerequisites for Using Generated Code
Choice of Environment for Varying Parameters
Between Sim ulation Runs
Comparison of Approaches Adapting Existing Models and MATLAB Code to Work with
Rapid Simulation
Varying Parameters Between Simulation Runs Using
MATLAB Code
Objective Procedure See Also
Varying Parameters Between Rapid Simulation
Runs
Objective Prerequisites Procedure For Further Information
........................................ 15-5
................ 15-5
....................... 15-5
........................... 15-7
............. 15-9
........................ 15-10
.......................... 15-10
............................... 15-11
.................................. 15-13
........................................ 15-13
........................................ 15-13
......................................... 15-14
........................................... 15-15
........................................ 15-15
..................................... 15-15
........................................ 15-15
............................ 15-17
.. 15-5
xviii Contents
Designing Models to Accept Event-Based Data During
Rapid Simulation
................................ 15-18
Event-Based Data for Rapid Simulations .............. 15-18
Varying the Stream of Random Numbers Varying Intergeneration Times Varying Attribute Values Varying Service Times Varying Timeout Intervals Varying Event-Based Signals
Example: Computing an Ensemble Average Using
MATLAB Code
Example: Varying the Number of Servers Using
MATLAB Code
Example: Computing an Ensemble Average Using
Rapid Simulation
Example Scenario Prerequisites Steps in the Example Results
Example: Varying Attribute Values Between Runs
Using Rapid Simulation
Example Scenario Prerequisites Steps in the Example Results
..................................... 15-32
.......................................... 15-35
..................................... 15-37
.......................................... 15-42
............................. 15-23
.................................. 15-26
.................................. 15-29
................................ 15-32
................................. 15-32
.............................. 15-32
................................. 15-37
.............................. 15-37
...................... 15-21
........................... 15-22
.......................... 15-24
........................ 15-25
.......................... 15-37
.............. 15-21
Example: Varying Queue Capacity Between Runs Using
Rapid Simulation
Example Scenario Prerequisites Steps in the Example Results
Limitations of Rapid Simulation for Discrete-Event
Simulations
.......................................... 15-47
................................ 15-43
................................. 15-43
..................................... 15-43
.............................. 15-43
..................................... 15-48
xix
16
Learning More About SimEvents Software
Event Sequencing ................................. 16-2
Processing Sequence for Simultaneous Events Role of the Event Calendar For Further Information
Choosing How to Resolve Simultaneous Signal
Updates
........................................ 16-7
.......................... 16-3
............................ 16-5
.......... 16-2
Resolution Sequence for Input Signals
Detection of Signal Updates Effect of Simultaneous Operations Resolving the Set of Operations Specifying Event Priorities to Resolve Simultaneous Signal
Updates
Resolving Si multaneous Signal Updates Without Specifying
Event Priorities
For Further Information
Livelock Prevention
Overview Permitting Large Finite Numbers of Simultaneous
Events
Notifications an d Queries Among Blocks
Overview of Notifications and Queries Querying Whether a Subsequent Block Can Accept an
Entity
Notifying Blocks About Status Changes
Notifying, Mo nitorin g, and Reactive Ports
Overview o f Signal Input Ports of SimEvents Blocks Notifying Ports Monitoring Ports Reactive Ports
....................................... 16-10
................................. 16-12
............................... 16-16
........................................ 16-16
........................................ 16-16
......................................... 16-18
................................... 16-21
.................................. 16-22
.................................... 16-23
......................... 16-8
.................... 16-9
...................... 16-10
............................ 16-15
.............. 16-8
............ 16-18
................ 16-18
............... 16-19
........... 16-21
..... 16-21
xx Contents
Interleaving of Block Operations
Overview o f Interleaving of Block Operations
.................... 16-25
........... 16-25
How Interleaving of Block Operations Occurs .......... 16-25
Example: Sequence of Departures and Statistical
Updates
....................................... 16-26
Zero-Duration Values and Time-Based Blocks
Techniques for Working with Multivalued Signals Example: Using a #n Signal as a Trigger
Update Sequence for Output Signals
Determining the Update Sequence Example: Detecting Changes in the Last- Updated
Signal
Storage and Nonstorage Blocks
Storage Blocks Nonstorage Blocks
......................................... 16-35
..................... 16-37
.................................... 16-37
................................. 16-37
.............. 16-32
................ 16-34
................... 16-34
........ 16-31
....... 16-31
Examples
A
Attributes of Entities .............................. A-2
Counting Entities
.................................. A-2
Working with Events
Queuing Systems
Working with Signals
Server States
Routing Entities
Batching
.......................................... A-3
.................................. A-2
...................................... A-3
................................... A-3
............................... A-2
.............................. A-3
xxi
Gates ............................................. A-3
Timeouts
Discrete Event Subsystems
Troubleshooting
Statistics
Timers
Rapid Simulation
.......................................... A-4
................................... A-4
.......................................... A-5
............................................ A-5
.................................. A-5
......................... A-4
Index
xxii Contents

Working with Entities

“Generating Entities When Events Occur” on page 1-2
“Specifying Generation Times for Entities” on page 1-5
“Setting Attributes of Entities” on page 1-7
“Manipulating Attributes of Entities” on page 1-13
“Accessing Attributes of Entities” on page 1-18
“Counting Entities” on page 1-20
“Combining Entities” on page 1-25
1
“Replicating Entities on Multiple Paths” on page 1-33
1 Working with Entities

Generating Entities When Events Occur

In this section...
“Overview” on page 1-2
“Sample Use Cases for Event-Based Generation of Entities” on page 1-2

Overview

The Event-Based Entity Generator block enables you to generate entities in response to signal-based events that occur during the simulation. The Generate entities upon parameter of the block determines:
The kind of signal input port the block has
The kinds of events that cause the block to generate an entity
Event times and the time intervals between pairs of successive entities are not necessarily predictable in advance.
1-2
Note The Event-Based Entity Generator block can respond to triggers and function calls. However, do not place the block inside a triggered or function-call subsystem. Like other blocks that possess e ntity ports, the Event-Based Entity Generator block is not valid inside a tri ggered or function-call subsystem.
To specify intergeneration times between pairs of successive entities instead of using an event-based approach, use the Time-Based Entity Generator block. For more information, see “Creating Entities Using Intergeneration Times” in the SimEvents
®
getting started documentation.

Sample Use Cases for Event-Based Generation of Entities

Generating entities when events occur is appropriate if you want the dynamics of your model to determine when to generate entities. For example,
Generating Entities When Events Occur
To generate an entity each time the length of a queue changes, configure
the queue to output a signal indicating the queue length. Then configure the Event-Based Entity Generator block to react to changes in the value of that signal.
To generate entities periodically, configure the Event-Based Entity
Generator b lock to react to sample time hits of a discrete- t ime signal with an explicit Sample time parameter. Regardless of the value of the signal, the block generates an entity periodically, according to the sample tim e of the driving block.
Another wa Generator of using t synchron possibl
For othe desired Priorit
To gene
Atosta trans to eac
To gen
shold, configure the Event-Based Entity Generator block to react to
thre
gers. Connect the tr signalinputportoftheblocktothestatistical
trig
al minus the threshold. If the statistical signal is an event-based
sign
al, then perform the subtraction in a discrete event subsystem; see
sign
ming Issues in SimEvents Models” on page 10-2 for details.
“Ti
he following figure, the Event-Based E ntity Generator block generates
In t
w entity each time the average waiting time of the queue crosses a
ane
reshold. The threshold is 5 s.
th
y to generate entities periodically is to use a Time-Based Entity
block with Distribution set to
Constant. The advantage
he Event-Based Entity Generator is that it more directly
izes entity generation events with sample time hits and avoids
e roundoff e rrors.
r examples that use this entity-generation method to create
simultaneity of events, see “Example: Choices of Values for Event
ies” on page 3-11.
rate an entity each time a Stateflow
®
chart transitions from state
te B, configure the chart to output a function call upon such a
ition. Then configure the Event-Based Entity G enerator block to react
h function call by generating an entity.
erate an entity each time a real-valued statistical signal crosses a
1-3
1 Working with Entities
Top- L e vel M o del
The subsystem between the queue and the entity generator adds -5 to the averagewaitingtimevaluetotranslatethethresholdfrom5to0.
1-4
Subsys
To gene
Entit port t the Pr
Note
the a simu ins ent for
tem Contents
rate multiple entities simultaneously, configure the Event-Based
y Generator block to react to function calls. Then connect its fcn input
o a signal that represents multiple function calls. For an example, see
eload Queue with Entities demo.
If you generate multiple entities simultaneously, then consider
ppropriateness of other blocks in the model. For example, if three
ltaneously generated entities advance to a single server, then consider
erting a q ueue between the generator and the server. As a result,
ities (in particular, the second and third entities) have a place to wait
theservertobecomeavailable.

Specifying Generation Times for Entities

In this section...
“Overview” on page 1-5
“Procedure for Generating E ntitie s at Specified Times” on page 1-5

Overview

If you have a list of unique times, you can configure the Time-Based Entity Generator block to generate entities at these times. Explicit entity-generation times are useful if you want to
Recreate an earlier simulation whose intergeneration times you saved
using a Discrete Event Signal to Workspace block.
Study the behavior of your model under unusual circumstances and have
created a series of entity generation times that you expect to produce unusual circumstances.
Specifying Generation Times for Entities
Verify simulation behavior that you or someone else observed elsewhere,
such as a result reported in a paper.

Procedure for Generating Entities at Specified Times

To generate entities at specified times, follow this procedure:
1 In the Time-Based Entity Generator block, set the Generate entities
with parameter to port labeled t appears on the block.
2 Depending on whether you want to generate an entity at T=0, either select
or clear the Generate entity at simulation start option.
3 Create a column vector, gentimes,thatlists0 followed by the nonzero
times at which you want to create entities, in strictly ascending sequence. You can create this vector using one of these techniques:
Enter the definition in the MATLAB
Load a MAT-file that you previously created
Intergeneration time from port t.Asignalinput
®
Command Window
1-5
1 Working with Entities
Manipulate a variable that a To Workspace or Discrete Event Signal to
Workspace block previously created
An example of a column vector listing generation times is:
gentimes = [0; 0.9; 1.7; 3.8; 3.9; 6];
4 Apply the diff function to the vector of generation times, thus creating
a vector of intergeneration times.
intergentimes = diff(gentimes);
5 Insert an Event-Based Sequence block in the model and connect it to the t
input port of the Time-Based Entity Generator block.
1-6
6 In the Ev
interge
paramet
he gene ration process if the simulation time e xceeds your maximum
halts t genera
tion time.
ent-Based Sequence block, set Vector of output values to
ntimes
er to
.SettheForm output after final data value by
Setting to infinity.TheSetting to infinity option

Setting Attributes of Entities

In this section...
“Role of Attributes in SimEvents Models” on page 1-7
“Blocks That Set Attributes” on page 1-8
“Attribute Value Support” on page 1-9
“Example: Setting Attributes” on page 1-10

Role of Attributes in SimEvents Models

You can attach data to an entity using one or more attributes of the entity. Each attribute has a name and a numeric value. You can read or change the values of attributes during the simulation.
For example, suppose your entities represent a message that you are transmitting across a communication network. You can attach the length of each particular message to the message itself, using an attribute named
length.
Setting Attributes of Entities
In some modeling situations, it is important to attach data to an entity instead of merely creating the data as the content of a signal. The next example shows the importance of considering not only the topology of your block diagrams, but also the timing of data signals.
Example: Reusing Data
Consider a queue-server example with varying service times. Suppose you want to plot the service time against entity count for each entity departing from the server. A signal specifies the service time to use for each entity. Although connecting the same signal to the Signal Scope block appears correct topologically, the timing in such an arrangement is incorrect. The incorrectness arises from the delay at the server. That is, the signal has one value when a given entity arrives at the server and another value when the same entity arriv es at the scope.
Toimplementtheexamplecorrectly,attachtheservicetimetoeachentity using an attribute and retrieve the attribute value when needed from each entity. That way, the scope receives the serv ice time associated with each
1-7
1 Working with Entities
entity, regardless of the delay between arrival times at the server and the scope.
1-8

Blocks That Set Attributes

To assign attributes on each arriving entity, use one of the blocks in the next table.
Block Attrib
Attribute Function
Set Attribute Signal value or information
ute Value
Value of output argument from a function you write
you enter in the block dialog box
For More Information
“Writing Functions to Manipulate Attributes” on page 1-13
Set Attribute block reference page
Setting Attributes of Entities
Block Attribute Value
Entity Departure Counter
Single Server
Assignments can create new attributes or change the values of existing attributes.
To learn how to query entities for attribute values, see “Accessing Attributes of Entities” on page 1-18. To learn how to aggregate attributes from distinct entities, see “Combining Entities” on page 1-25.
Entity count, only if you set
Write count to attribute
to
On.
Residual service time, only for preempted entities
For More Information
“Associating Each Entity with Its Index” on page 1-24
“Preempting an Entity in a Server” on page 5-11

Attribute Value Support

These lists summarize the characteristics of attribute values.

Permitted Characteristics of Attribute Values

Real or complex
Array of any dimension
double data type
For a given attribute, the characteristics of the value must be consistent throughout the model.

Not Permitted as Attribute Values

Frame
Structure
Data types other than
attribute values.
Buses
double. In particular, strings are not valid as
1-9
1 Working with Entities
Attribute Name
Count
Type
Example: Settin
This example ill entities.
After each entity d eparts from the Attribute Function block, it possesses the attributes listed in the table.
Attribute Value
N, for the Nth entity departing from the Time-Based Entity Generator block
Constant value of3A1 row of table in Set Attribute dialog box:
ustrates different ways of assigning attribute values to
g Attributes
Method for Setting Attribute Value
In Entity Departure Counter dialog box:
Write count to attribute = Attribute name = Count
Actually, the entity generator creates the Count attribute with a value of sets the attribute value according to the entity count.
0. The Entity Departure Counter block
On
1-10
Name = Value From = Dialog Value = 3
Type
Setting Attributes of Entities
Attribute Name
Length
LengthInt
Attribute Value
Next number in the sequence produced by
Method for Setting Attribute Value
Event-Based S equence block connected to Set Attribute block in which A2 row of table in dialog box is con fi gu red
as follows: Event-Based Sequence block
Name =
Length
Value From = Signal port
floor(Length) Attribute Function block whose function is
function [out_LengthInt] = fcn(Length) out_LengthInt = floor(Length);
In this example, each Attribute Scope block plots values of a different attribute over time. Notice from the vertical axes of the plots below that the
Count
values increase by 1 with each entity , the Type values are constant, and the
Length values show cyclic repetition of a sequence. For brevity, the example
does not plot
LengthInt values, which would look similar to Length values.
1-11
1 Working with Entities
1-12

Manipulating Attributes of Entities

In this section...
“Writing Functions to Manipulate Attributes” on page 1-13
“Using Block Diagrams to Manipulate Attributes” on page 1-15

Writing Functions to Manipulate Attributes

To manipulate attributes via code, use the Attribute Function block. The block lets you access existing attributes of the arriving entity, modify the values of existing attributes, or create new attributes.
For examples that use the block, see
“Example: Setting Attributes” on page 1-10
“Attribute Names Unique and Accessibl e in Composite Entity” on page 1-29.
Entity Combiner for Assembling Components demo
Manipulating Attributes of Entities
Distributed Processing for Multi-Class Jobs demo, within the Distribution
Center subsystem and its Service History Monitor subsystem
Procedure for Using the Attribute Function Block
The Attribute Function block has one entity input port and one entity output port. The block manipulates attributes of each arriving entity. To edit the computation, use this procedure:
1 Display the block’s associated function in an editor window by
double-clicking the Attribute Function block.
2 Write the first line o f the function using arguments that reflect the
attributes that the function manipulates. The arguments do not reflect input or output signals.
1-13
1 Working with Entities
Argument-Naming Rules
Input argument names must match the entity’s attribute names.
Output argument names must be
out_ followed by the names of
attributes to assign to the departing entity.
The entity must possess any attributes named as input arguments of the function. If the entity does not possess an attribute named using an output argument of the function, then the block creates the attribute.
The default function definition, below, indicates that the function called
fcn uses the value of the attribute called Attribute1 to compute values of
the attributes called
function [out_Attribute1, out_Attribute2] = fcn(Attribute1)
3 Write the function to implement your specific computation. The value of
Attribute1 and Attribute2.
each a ttribu t e can b e a real- or com p lex-valued array of any dimension and double data type, but cannot be a structure or frame. For each attribute, the d imensions and complexity must be consistent throughout the model. Also, the function must use the Embedded MATLAB
®
subset. For more information, see “Overview of the Embedded MATLAB Subset” in the Embedded MATLAB documentation.
Note If you try to update the diagram or run the simulation for a model that contains the Attribute Function block, then y ou must have write access to the current folder because the application creates files there.
1-14
Example: Incorporating Legacy Code
Suppose you already have a file that defines a function that:
Represents your desired attribute manipulation
Uses the Embedded MATLAB subset
Manipulating Attributes of Entities
The function might or might not satisfy the argument-naming rules for the Attribute Function block. This example illustrates a technique that can help you satisfy the naming rule while preserving your legacy code.
1 The top le vel of the function associated with the Attribute Function block
must satisfy the argument-naming rule. In this example, the function reads the entity’s called
x. The function assigns a new value to the entity’s x attribute, so the
function’s output argument must be called
function out_x = update_x _attribute(x)
2 Using the variable names x and out_x, invoke your legacy code. The usage
below a ssumes that you have called the function
out_x = mylegacyfcn(x);
3 Include your legacy code as either a subfunction or an extrinsic function; see
x attribute, so the function’sinputargumentmustbe
out_x.
mylegacyfcn.
“Calling Functions” in the Embedded MATLAB documentation for details.
In your legacy code, the function name and the number of input and output arguments must be compatible with the invocation above. However, the legacy code does not need to follow the argument-naming rules for the Attribute Function block. Below is an example of a function that is compatible with the invocation above.
function outp = mylegacyf cn(inp)
if inp < 0
outp = 0;
else
if ((inp >= 0) && (inp < 1))
outp = 0.25;
else
outp = 5;
end
end

Using Block Diagrams to Manipulate Attributes

To manipulate attributes using blockstoperformthecomputation,usean arrangement as in the following figure.
1-15
1 Working with Entities
Top- L e vel M o del
Subsystem Contents
1-16
In your own model, you can vary:
The number of outputs of the Get Attribute block
The number of inputs of the Set Attribute block
The connections or contents of the D iscre te Event Subsystem block
The key components are in the table.
Block Role
Get Attribute Queries the entity for its attribute
value.
Discrete Event Subsystem Ensures correct timing of the
computation inside the subsystem, given that the output signal from the Get Attribute block is an e ven t- ba sed signal. Other signals, if any, in the computation can be event-based or time-based. To learn more about discrete event subsystems, see
Block Role
Chapter 10, “Controlling Timing with Subsystems”.
Manipulating Attributes of Entities
Content of the discrete event subsystem
Models your specific computation.
The earlier figure shows one example: 5|Attr+t|, where Attr is an attribute value and t is a signal value unrelated to attributes. The configuration of the subsystem causes it to execute if and o n ly if Attr has a sample time hit.
Single Server with Service time set to
0
Ensures that the Set Attribute block uses the up-to-date results of the computation. For details, see “Interleaving of Block Operations” on page 16-25.
Set Attribute Assigns new value to the attribute.
1-17
1 Working with Entities

Accessing Attributes of Entities

The table describes some w ays you can access and use data that you have attached to an entity.
UseAttributeValuesTo... Technique
Create a signal Use the Get Attribute block.
Create a plot Use the Attribute Scope block and name
For example, see the subsystem of the model described in “Adding Event-Based Behavior” in the SimEvents getting started documentation.
the attribute in the Y attribute name parameter of the block.
Alternatively, use the X-Y Attribute Scope block and name two attributes in the X attribute name and Y attribute name parameters of the block.
1-18
Compute a different attribute value
Help specify behavior of a block that supports the use of attribute values for block parameters. Examples are the service time for a server and the selected port for an output switch.
For example, see the reference page for the X-Y Attribute Scope block.
Use the Attribute Function block.
For example, see “Attribute Names Unique and Accessible in Com posite Entity” on page 1-29.
Name the attribute in the block dialog box as applicable.
For example, see “Example: Using an Attribute to Select an Output Port” in the SimEvents getting started d ocumentation.
Accessing Attributes of Entities
Tip Suppose your entity possesses an attribute containing one of these quantities:
Service time
Switching criterion
Another quantity that a block can obtain from either an attribute or signal
Use the attribute directly. This is better than creating a signal with the attribute value and ensuring that the signal is up-to-date when the entity arrives. For a comparison of the two approaches, see “Example: Using a Signal or an Attribute” on page 14-78.
1-19
1 Working with Entities

Counting Entities

In this section...
“Counting Departures Across the Simulation” on page 1-20
“Counting Departures per Time Instant” on page 1-20
“Resetting a Counter Upon an Event” on page 1-22
“Associating Each Entity with Its Index” on page 1-24

Counting Departures Across the Simulation

Use the #d or #a output signal from a block to learn how many entities have departed from (or arrived at) a particular block . The output signal also indicates when departures occurred. This method of counting is cumulative throughout the simulation. These examples use the #d output signal to count departures:
“Building a Simple Discrete-Event Model” in the SimEvents getting started
documentation
1-20
“Example: First Entity as a Special Case” on page 8-11
“Stopping Upon Processing a Fixed Number of Entities” on page 12-36

Counting Departures per Time Instant

Suppose you want to visualize entity departures from a particular block, and you w ant to reset (that is, restart) the counter at each time instant. Visualizing departures per time instant can help you:
Detect simultaneous departures
Compare the number of simultaneous departures at different time instants
Visualize the departure times while keeping the plot axis manageable
Use the Instantaneous Entity Counting Scope to plot the number of entities that have arrived at each time instant. The block restarts the count from 1 when the time changes. A s a result, the count is cumulative for a given tim e instant, but not cumulative across the entire simulation.
Counting Entities
Example: Counting Simultaneous Departures from a Server
In this example, the Infinite Server block sometimes completes service o n multiple entities simultaneously. The Instantaneous Entity Counting Scope indicates how many en tities departed from the server at each fixed time instant during the simulation.
1-21
1 Working with Entities

Resetting a Counter Upon an Event

Suppose you want to count entities that depart from a particular block, and you want to reset the counter at arbitrary times during the simulation. Resetting the counter can help you compute statistics for evaluating your system over po rtions of the simulation.
1-22
The Entity Departure Counter block counts entity departures via a resettable counter. To configure the block:
1 Decide w hich type of events you want to reset the counter. The choices are:
Sample time hits
Trigger edges
Value changes
Function calls
These resources can help you choose w hich type of events:
To learn the difference among the kinds of signal-based events, see
“Signal-Based Events” on page 2-4 and “Function Calls” on page 2-8.
To build a signal that has events at the times that you need them, see
“Manipulating Events” on page 2-32.
To visualize the events of a signal, use the Instantaneous Event
Counting Scope block.
Counting Entities
2 In the Entity Departure Counter block, indicate which signal-based events
cause the counter to reset:
To reset upon sample time hits of an input signal, set Reset counter
upon to
Sample time hit from port ts.
To reset based on a trigger edge in an input signal, set Reset counter
upon to
Falling,orEither.
Trigger from port tr.ThensetTrigger type to Rising,
To reset based on a change in the value of an input signal, set Reset
counter upon to change in signal value to
Change in signal from port vc.ThensetType of
Rising, Falling,orEither.
To reset upon function calls, set Reset counter upon to
call from port fcn
3 If you want to specify an explicit priority for the reset event, select Resolve
.
Function
simultaneous signal updates according to event priority. Then enter the priority using the Event priority parameter.
4 Click OK or Apply . The block now has a signal input port.
5 Connect a signal to the signal input port.
During the simulation, the block counts departing entities and rese ts its counter whenever the input signal satisfies your specified event criteria.
Example: Resetting a Counter After a Transient Period
This example counts entity departures from a queuing system, but resets the counter after an initial transient period.
1-23
1 Working with Entities

Associating Each Entity with Its Index

Use the Entity Departure Counter block with Write count to attribute set to
On to associate entity counts with the entities that use a particular path.
The Nth entity departing from the Entity Departure Counter block has an attribute value of N.
1-24
For an example, see “Example: Setting Attributes” o n page 1-10.
For an example in which the Entity Departure Counter block is more straightforward than storing the #d ou tput signal in an attribute, see “Example: Sequence of Departures and Statistical Updates” on page 16-26.

Combining Entities

In this section...
“Overview of the Entity-Combining Operation” on page 1-25
“Example: Waiting to Combine Entities” on page 1-25
“Example: Co pying T i mers W hen Combining Entities” on pag e 1-27
“Example: Managing Data in Composite Entities” on page 1-28

Overview of the Entity-Combining Operation

You can combine entities from different paths using the Entity Combiner block. The entities you combine, called component entities, might represent different parts within a larger item, such as a header, payload, and trailer that are parts of a packet.
The Entity Combiner block and its surro unding blocks automatically detect when all necessary component entities are present and the result of the combiningoperationwouldbeabletoadvance to a storage block or a block that destroys entities. “Example: Waiting to Combine Entities” on page 1-25 illustrates these automatic interactions among blocks.
Combining Entities
The Entity Combiner block prov ides options for managing information (attributes and timers) associated with the component entities, as illustrated in “Example: Managing D ata in Composite Entities” on page 1-28. You can also configure the Entity Combiner block to make the combining opera ti on reversible via the Entity Splitter block.
For details about individual blocks, see the reference pages for the Entity Combiner and Entity Splitter blocks.

Example: Waiting to Combine Entities

The model below illustrates the synchronization of entities’ advancement by the Entity Combiner block and its preceding blocks.
1-25
1 Working with Entities
The combining operation proceeds w he n all of these conditions are simultaneously true:
1-26
The top queue has a pending entity.
The middle queue has a pending entity.
The bottom queue has a pending entity.
The entity input port of the Instantaneous Entity Counting Scope block is
available, which is true throughout the simulation.
The bottom entity generator has the largest intergeneration time among the t hree entity generators, and is the limiting factor that determ ines when the Entity Combiner block accepts one entity fro m each queue. The top and middle queues store pending entities while waiting for the bottom entity generator to generate its next entity.
If you change the uniform distribution in the middle entity generator to produce intergeneration times between 0.5 and 3, then the bottom entity generator is not consistently the slowest. Nevertheless, the Entity Combiner block autom atically permits the arrival of one entity from each queue as soon as each queue has a pending entity.
Combining Entities
While you could alternatively synchronize the departures from the three queues using appropriately configured gates, it is simpler and more intuitive to use the Entity Combiner block as shown.

Example: Copying Timers When C om bining Entities

The model below combines an entity representing a product with an entity representing a box, thus creating an entity that represents a boxed product. The Entity Combi ne r block copies thetimerfromtheproducttotheboxed product.
The model plots the products’ average age, which is the sum of the time that a product might wait for a box and the service time for boxed products in the Infinite Server block. In this simulation, some products wait for boxes, while some boxes wait for products. The generation of products and boxes are random processes with the same exponential distribution, but different seeds for the random number generator.
1-27
1 Working with Entities

Example: Managing Data in Composite Entities

This section illustrates the connection between access to a component entity’s attributes in a composite entity and uniqueness of the attribute names across all component entities.
Attribute Names Nonunique and Inaccessible in Composite Entity
The model below combines component entities representing a header, payload, and trailer into a composite entity representing a packet. Each component entity has a Entity Splitter block divides the packet into separate header, payload, and trailer entities, each has the appropriate attribute. However, accessible in the packet (that i s, after combining and before splitting). If it were, the name would be ambiguous because all component entities h ave an attribute by that name.
Length attribute that the packet stores. When the
Length is not
1-28
Combining Entities
Attribute Names Unique and Accessible in Composite Entity
The m odel below uniquely names all attributes of the components and makes them accessible in the packet. If your primary focus is on data rather than the entities that carry the data, then you can think of the Entity Combiner block as aggregating data from different sources.
1-29
1 Working with Entities
1-30
The model uses the Attribute Function block and its underlying function to illustrate these ways of accessing attributes via the composite entity.
Combining Entities
Attribute Operation Attribute Names
Read existing attributes of the component e ntities.
Change the value of an
HeaderLength PayloadLength TrailerLength
Status
existing attribute of a component. The new value persists when the Entity Splitter block divides the packet into its component entities.
Create a new attribute
PacketLength
on the composite entity, not associated with any of the component entities. The new attribute does not persist bey ond the Entity Splitter block.
Use of Attribute Function Block
Naming these attributes as input arguments o f the function causes the block to read these attributes of the arriving entity.
Naming out_Status as an output argument of the function causes the block to update the
Status attribute of the
entity.
Naming
out_PacketLength
as an output argument causes the block to create the
PacketLength attribute
on the entity.
Function Underlying the Attribute Function Block.
function [out_PacketLength, out_Status] = packet_length(HeaderLength,...
PayloadLength,TrailerLength)
%PACKET_LENGTH Sum the component lengths and set Status to 1.
out_PacketLength = HeaderLength + PayloadLength + TrailerLength;
out_Status = 1;
1-31
1 Working with Entities
Note The code does not distinguish between output arguments that define
new attributes and output arguments that define new values for existing attributes. Only by examining other blocks in the model could you determine that
Status is an existing attribute and PacketLength is no t.
1-32

Replicating Entities on M ultiple Paths

In this section...
“Sample Use Cases” on page 1-33
“Modeling Notes” on page 1-33

Sample Use Cases

The Replicate block enables you to distribute copies of an entity on multiple entity paths. Replicating entities might be a requirement of the situation you are modeling. For example, copies of messages in a multicasting communication system can advance to multiple transmitters or multiple recipients, as in the fragment below.
Replicating Entities on Multiple Paths
Similarly, copies of computer jobs can advance to multiple computers in a cluster so that the jobs can be processed in parallel on different platforms.
In some cases, replicating entities is a convenient modeling construct. For example, the MAC Controller subsystems in the Ethernet Local Area Network demo se nd one copy of an entity for processing and retain ano ther copy of the same entity for the purpose of observing the state of the channel.

Modeling Notes

Unlike the Output Switch block, the Replicate block has departures at all
of its entity output ports that are not blocked, not just a single selected entity output port.
1-33
1 Working with Entities
If your model routes the replicates such that they use a common entity
path, then be a w are that blockages can occur during the replication p rocess. For example, connecting all ports of a Replicate block, Path Combiner block, and Single Server block in that sequence can create a blockage because the server can accommodate at most one of the replicates at a time. The blockage causes fewer than the maximum number of replicates to depart from the block.
Each time the Replicate block replicates an entity, the copies depart in a
sequence w hose start is determined by the Departure port precedence parameter. Although all copies departatthesametimeinstant,the sequence might be significant in some modeling situations. For details, see the reference page for the Replicate block.
1-34

Working with Events

“Supported Events in SimEvents Models” on page 2-2
“Example: Event Calendar Usage for a Queue-Server M odel” on page 2-10
“Observing Events” on page 2-18
“Generating Function-Call Events” on page 2-28
“Manipulating Events” on page 2-32
To learn about working with sets of simultaneous events, see Chapter 3, “Managing Simultaneous Events”. To view information about events during the simulation, see Chapter 14, “Debugging Discrete-Event Simulations”.
2
2 Working with Events

Supported Events in SimEvents Models

In this section...
“Types of Supported Events” on page 2-2
“Signal-Based Events” on page 2-4
“Function Calls” on page 2-8

Types of Supported Events

An event is an instantaneous discrete incident that changes a state variable, an output, and/or the occurrence of other events. SimEvents software supports the events listed below.
Event
Counter r
Delayed restart
Entity advancement
Entity destruction
Entity generation
Entity request
eset
Descripti
Reinitia Departur
Causes a Entity G block u set Res
restar
Depar at ano
Arri outp
Cre Eve sus
tification that an entity input port has
No
come available. A preceding block’s response
be
the notification might result in an entity
to
dvancement. After each entity advancement, an
a
nabled Gate block o r a sw itch block reissues the
E
otification until no further entity advancement
n
an occur.
c
on
lization of the counter in the Entity
e Counter block.
pending entity in the Time-Based
enerator block to attempt to depart. The
ses d elayed restart events only when you
ponse when unblocked to
.
t
ture of an entity from one block and arrival
ther block.
val of an entity at a block that has no entity
ut port.
ation of an entity, except in the case of an
nt-Based Entity Generator block that has
pended the generation of entities.
Delayed
2-2
Supported Events in SimEvents®Models
Event
Function call
Description
Discrete invocation request carried from block to block by a special signal called a function-call signal. For more informatio n, see “Function Calls” on page 2-8.
Gate (opening or closing)
Memory read
Memory write
Port selection
Opening or closing of the gate represented by the Enabled Gate block.
Reading of memory in the Signal Latch block.
Writing of memory in the Signal Latch block.
Selection of a particular entity port in the Input Switch, Output Switch, or Path Combiner block. In the case of the Path Combiner block, the selected entity input port is the port that the block notifies first, whenever its entity output port changes from blocked to unblocked.
Preemption
Replacement of an entity in a server by a higher priority entity.
Release
Opening of the gate represented by the Release Gate block.
Sample time hit Update in the value of a signal that is connected
to a block configured to react to signal updates.
Service completion Completion of service on an entity in a server.
Storage completion Change in the state of the Output Switch block,
making it attempt to advance the stored entity.
Subsystem Execution of Discrete Event Subsystem block
contents caused by an appropriate signal-based event a t one of the subsystem’s inports.
Timeout
Departure of an entity that has exceeded a previously established time limit.
2-3
2 Working with Events
Event
Trigger
Value change
During a simulation, the application maintains a list, called the event calendar, of selected upcoming events that are scheduled for the current simulation time or future times. By referring to the event calendar, the application executes events at the correct simulation time and in an appropriate sequence.
Description
Rising or falling edge of a signal connected to a block that is configured to react to relevant trigger edges. A rising edge is an increase from a negative or zero value to a positive value (or zero if the initial value is negative). A falling edge is a decrease from a positive or a zero v alue to a negative value (or ze ro if the initial value is positive).
Change in the value of a signal connected to a block that is configured to react to relevant value changes.

Signal-Based Events

Sample time hits, value changes, and triggers are collectively called signal-based events. Signal-based events can occurwithrespecttotime-based or event-based signals. Signal-based events provide a mechanism for a block to respond to selected state changes in a signal connected to the block. The kind of state change to which the block responds determines the specific type of signal-based event.
2-4
When comparing the types of signal-based events, note that
The updated value that results in a sample time hit could be the same as or
different from the previous value of the signal.
Event-based signals do not necessarily undergo an update at the beginning
of the simulation.
Every change in a signal value is also an update in that signal’s value.
However, the opposite is not true because an update that merely reconfirms the same value is not a change in the value.
Supported Events in SimEvents®Models
Every rising or falling edge is also a change in the value of the signal.
However, the opposite is not true becauseachangefromonepositivevalue to another (or from one negative value to another) is not a rising or falling edge.
Triggers and value changes can be rising or falling. Y ou configure a block
to determine whether the block considers rising, falling, or either type to be a relevant occurrence.
Blocks in the Simulink
®
libraries are more restrictive than blocks in the SimEvents libraries regarding trigger edges that rise or fall from zero. Simulink blocks in discrete-tim e systems do not consider a change from zero to be a trigger edge unless the signal remained at zero for more than one time step; see “Triggered Subsystems” in the Simulink documentation. SimEvents blocks configured with tr ports consider any change from zero toanonzeronumbertobeatriggeredge.
Example: Comparing Types of Signal-Based Events
Consider the signal representing the number of entities stored in a FIFO queue. This is the #n output signal from the FIFO Queue block in the model below. The #n signal is connected to the Event-Based Entity Generator block, which reacts to dif fere n t types of signal-based events. Parameters in its dialog box determine w h ether the block has a ts, vc,ortr input port, as well as the types of events to which the block reacts.
In the following figures, a staircase plot shows the values of the #n signal, starting from the first entity’s arrival at T=0. Based on those values of #n,the stem plots indicate when signal-based events occur at the Event-Based Entity Generator block if it is configured with a ts, vc,ortr signal input port.
2-5
2 Working with Events
2-6
Sample Time Hits of #n Signal Connected to ts Port
Supported Events in SimEvents®Models
Value Changes of #n Signal Connected to vc Port
2-7
2 Working with Events
2-8
Trigger Ed ges of #n Signal Connected to tr Port

Function Calls

Function calls are discrete invocation requests carried from block to block by a special signal called a function-call signal. A function-call signal appears as a dashed line, not a solid line. A function-call signal carries a function call at discrete times during the simulation and does not have a defined value at other times. A function-call signal is capable of carrying multiple function calls at the same value of the simulation clock, representing multiple simultaneous events.
In SimEvents models, function calls are the best w ay to make Stateflow blocks and blocks in the Simulink libraries respond to asynchronous state changes.
Function calls can come from these kinds of blocks:
Event generator blocks or Function-Call Generator blocks
Event translation blocks
Stateflow blocks
Supported Events in SimEvents®Models
Embedded MATLAB Function blocks
You can combine or manipulate function-call signals. To learn more, see “Manipulating Events” on page 2-32.
2-9
2 Working with Events

Example: Event Calendar Usage for a Queue-Server Model

In this section...
“Overview of Example” on page 2-10
“Start of Simulation” on page 2-11
“Generation of First Entity” on page 2-11
“Generation of Second Entity” on page 2-12
“Completion of Service Time” on page 2-13
“Generation of Third Entity” on page 2-14
“Generation of Fourth Entity” on page 2-15
“Completion of Service Time” on page 2-16

Overview of Example

To see how the event calendar drives th e simulation of a simple event-based model, consider the queue-server model depicted below.
2-10
Assume that the blocks are configured so that:
The Time-Based En tity Generator block generates an entity at T =0.9,1.7,
3.8, 3.9, and 6.
Example: Event Calendar Usage for a Queue-Server Model
The queue has infinite capacity.
The server uses service times of 1.3, 2.0, and 0.7 seconds for the first three
entities.
The sections below indicate ho w the event calendar and the system’s states change during the simulation.

Start of Simulation

When the sim ulation starts, the queue and server are empty. The entity generator schedules an event for T = 0.9. The event calendar looks like the table below.
Time of Event (s)
0.9
Type of Ev ent
Time-Based Entity Generator block generates an entity.

Generation of First Entity

At T =0.9,
The entity generator generates an entity and attempts to output it.
The queue is empty, so the entity advances from the entity generator to
the queue.
The newly generated entity is the only one in the queue, so the queue
attempts to output the entity. It queries the server to determine whether theservercanaccepttheentity.
The server is empty, so the entity advances from the queue to the server.
The server’s entity input port becomes temporarily unavailable to future
entities.
The server schedules an event that indicates when the entity’s service time
is completed. The service time is 1.3 seconds, so service is com plete at T =2.2.
The entity generator schedules its next entity-generation event, at T =1.7.
2-11
2 Working with Events
In the schematic below, the circled notation “e1” depicts the first entity and the dashed arrow is meant to indicate that this entity advances from the entity generator through the queue to the server.
e1
The event calendar looks like this.
2-12
Time of Event (s)
1.7
2.2
Event Description
Time-Based Entity Generator block generates second entity.
Single Serv er block co m pletes service on the first entity.

Generation of Second Entity

At T =1.7,
The entity generator generates an entity and attempts to output it.
The queue is empty, so the entity advances from the entity generator to
the queue.
The newly generated entity is the only one in the queue, so the queue
attempts to output the entity. However, the server’s entity input port is unavailable, so the entity stays in the queue. The queue’s entity output port is said to be blocked because an entity has tried and failed to depart via this port.
Example: Event Calendar Usage for a Queue-Server Model
The entity generator schedules its next entity-generation event, at T =3.8.
e2 e1
Time of Event (s)
2.2
3.8
Event Description
Single Serv er block co m pletes service on the first entity.
Time-Based Entity Generator block generates the third entity.

Completion of Service T ime

At T =2.2,
The server finis hes servin g its en t ity and attempts to output it. The server
queries the next block to determine whether it can accept the entity.
The sink block accepts all entities by definition, so the e n tity advances
fromtheservertothesink.
The server’s entity input port becomes available. The server executes an
event to notify the queue about the newly available entity input port. This is called an entity request event.
The queue is now able to output the second entity to the server. As a result,
the queue becomes empty and the server becomes busy again.
The server’s entity input port becomes temporarily unavailable to future
entities.
2-13
2 Working with Events
The server schedules an event that indicates when the second entity’s
servicetimeiscompleted. Theservicetimeis2.0seconds.
Note The server’s entity input port started this time instant in the unavailable state, became available (when the first entity departed from the server), and then became unavailable once again (when the second entity arrived at the server). It is not uncommon for a state to change more than onceinthesametimeinstant.
2-14
Time of Event (s)
3.8
4.2
e2
Event Description
Time-Based Entity Generator block generates the third entity.
Single Serve r block completes service on the second entity.
e1

Generation of Third Entity

At T =3.8,
The entity generator generates an entity and attempts to output it.
The queue is empty, so the entity advances from the entity generator to
the queue.
Example: Event Calendar Usage for a Queue-Server Model
The newly generated entity is the only one in the queue, so the queue
attempts to output the entity. However, the server’s entity input port is unavailable, so the entity stays in the queue.
The entity generator schedules its next entity-generation event, at T =3.9.
e1e2e3
Time of Event (s)
3.9
4.2
Event Description
Time-Based Entity Generator block generates the fourth entity.
Single Serve r block completes service on the second entity.

Generation of Fourth Entity

At T =3.9,
The entity generator generates an entity and attempts to output it.
The queue is not full, so the entity advances from the entity generator
to the queue.
The server’s entity input port is still unavailable, so the queue cannot
output an entity. The queue length is currently two.
The entity generator schedules its next entity-generation e vent, at T =6.
2-15
2 Working with Events
e1e2e3e4
Time of Event (s)
4.2
6
Event Description
Single Serve r block completes service on the second entity.
Time-Based Entity Generator block generates the fifth entity.

Completion of Service T ime

At T =4.2,
The server finishes serving its ent i ty and attempts to output it.
The sink block accepts all entities by definition, so the e n tity advances
fromtheservertothesink.
The server’s entity input port becomes available, so it executes an entity
request event. The queue’s entity output port becomes unblocked. The queue is now able to output the third entity to the server. As a result, the queue l ength becomes one, and the server becomes busy.
The server’s entity input port becomes temporarily unavailable to future
entities.
The server schedules an event that indicates when the entity’s service time
is completed. The service time is 0.7 seconds.
2-16
Example: Event Calendar Usage for a Queue-Server Model
The queue attempts to output the fourth entity. However, the server’s
entity input port is unavailable, so this entity stays in the queue. The queue’s entity output port becomes blocked.
Note The queue’s entity output port started this time instant in the blocked state, became unblocked (when it sensed that the server’s entity input port became available), and then became blocked once again (when the server began serving the third entity).
Time of Event (s)
4.9
6
e1e2e3e4
Event Description
Single Serv er block completes service on the third entity.
Time-Based Entity Generator block generates the fifth entity
2-17
2 Working with Events

Observing Events

In this section...
“Techniques for Observing Events” on page 2-18
“Example: Obs erving Service Completions” on page 2-22
“Example: D etecti ng Collisions by Comparing Events” on page 2-25

Techniques for Observing Events

The SimEvents debugger can help you observe events and the relative sequencing of simultaneous events. For details, see “Overview of the SimEvents Debugger” on page 14-3.
The next table describes some additional observation techniques. Each technique focuses on a particular kind of event. These techniques indicate the simulation time at which events occur but do not indicate relative sequencing of simultaneous events. Key tools are the Instantaneous Event Counting Scope block, Signal Scope block, and Discrete Event Signal to Workspace block. You can also build a discrete event subsystem that counts events and creates a signal, as illustrated in “Example: Focusing on Events, Not Values” on page 10-23.
2-18
Event
Counter reset In the counter block #d output signal, observe falling
Delayed restart
ity
Ent
vancement
ad
tity
En
struction
de
Observation Technique
edges. Alternatively, use a branch line to connect the input signal to an Instantaneous Event Counting Scope block.
In the block from which the entity departs, observe increases in the #d output signal.
In the Entity Sink block, observe increases in the #a output signal. The Instantaneous Entity Counting Scope block provides a plot in place of a #a signal.
Observing Events
Event
Entity generation
Entity request
Function call
Observation Technique
In the entity generator block, observe values of the pe and #d output signals. Upon entity generation, you see one of the following outcomes:
The generated entity departs immediately. #d
increases and pe does no t change.
The generated entity cannot depart immediately. pe
increases.
To build a concrete example, adapt the technique described in “Example: Observing Service Completions” on page 2-22.
If the block issuing the fu n cti on call provides a #f1 output signal, observe its increases. Otherwise, configure a Signal-Based Function-Call Event Generator blockbyenablingthe#f1 output port and setting Generate function call only upon to
from port fcn
. Insert the Sig n al-B as ed Function-Call
Function call
Event Generator block between the block issuing the function call and the block reacting to the function call.
Gate (opening or closing)
Memory read
Memory write
Port selection
In the Enabled Gate block, use a branch line to connect the en input signal to an Instantaneous Event Counting Scope block. Rising trigger edges of the input signal indicate gate-opening events, while f a lling tri gger edges of the input signal indicate gate-closing events.
IntheSignalLatchblock,observesampletimehitsin the out output signal.
IntheSignalLatchblock,observesampletimehitsin the mem output signal..
If the block has a p input signal, use a branch line to connect the p signal to an Instantaneous Event Counting Scope block that is configured to plot value changes. FortheInputSwitchorOutputSwitchblock, an alternative i s to observe the last output signal.
2-19
2 Working with Events
Event
Preemption In the server block, observe increases in the #p output
Release
Sample time hit
Service completion
Observation Technique
signal.
In the Release Gate block, use a branch line to connect the input signal to an Instantaneous Event Counting Scope block.
Use a branch line to connect the signal to an Instantaneous Event Counting Scope block.
For Single Server blocks, observe values of the pe and #d output signals. Upon service completion, you see one of the following outcomes:
The entity departs immediately. #d increases, and
pe does not change.
The entity canno t depart immediately. pe increases.
To build a concrete example, adapt the technique described in “Example: Observing Service Completions” on page 2-22.
For Infinite Server and N-Server blocks, observe values of the #pe and #d output signals. Upon service completion, y ou see one of the following outcomes:
2-20
The entity departs immediately. #d increases, and
#pe does not change.
The entity cannot depa rt immediately. #pe increases.
For a concrete example, see“Example: Observing Service Completions” on page 2-22.
Observing Events
Event
Storage completion
Observation Technique
In the sw itch block, observe values of the pe and #d output signals. Upon storage completion, you see one of the following outcomes:
The entity departs immediately. #d increases, and
pe does not change.
The entity canno t depart immediately. pe increases.
To build a concrete example, adapt the technique in “Example: Observing Service Completions” on page 2-22.
Subsystem In any output signal from the subsystem, observe
sample time hits. Alternatively, connect a Discrete Event Signal to Workspace block to any signal inside the subsystem. Then observe the times at which the variable in the workspace indicates a sample time hit of the signal.
Timeout
In the storage block from which the entity times out, observe increases in the #to output signal.
Trigger Useabranchlinetoconnectthesignaltoan
Instantaneous Event Counting Scope block.
Valuechange Useabranchlinetoconnectthesignaltoan
Instantaneous Event Counting Scope block.
For examples that use one or more of these techniques, see:
“Example: Plotting Event Counts to Check for Simultaneity” on page 11-15
“Example: Observing Service Completions” on page 2-22
“Example: Focusin g on Events, Not Values” on page 10-23
Also, “Example: Detecting Collisions by Comparing Events” on page 2-25 describes how to use a Signal Latch block to observe which of two types of events are more recent.
2-21
2 Working with Events
Example: Observ
The following ex completes servi to the M ATLA B wo occurred.
ample creates a stem plot showing when an N-Server block
ce on each entity. The example also writes a signal,
ing Service Completions
num_svc,
rkspace that indicates when each service completion
Example Results
The example produces a plot in which each stem indicates a service completion. The timing depends on the entity generation, service completion, gate opening, and gate closing times in the model.
2-22
After the sim ulation is over, to form a vector of service completion times, enter the following code:
t_svcp = num_svc.time
The output is:
t_svcp =
0.4542
0.9077
1.1218
1.3868
2.3430
2.3570
2.9251
2.9370
3.5592
4.3933
4.8554
Computation Details
In the model, these blocks jointly d ete rmine when service completions occurred:
Observing Events
Discrete Event Subsystem
Signal-Based Event to Function-Call Event
As inputs, the subsystem uses the #d and #pe output signals from the server block.
Tip To adapt this technique to blocks that have a pe but not a #pe output signal, use pe.
The subsystem executes when either #d or #pe increases because a service completion has one of these consequences:
The entity departs immediately. #d increases, while #pe does not change.
The entity cannot depart immediately, so it becomes a pending entity. #pe
increases, while #d does not change.
2-23
2 Working with Events
Inside the subsystem is the Embedded MA TLAB Function block. It contains this code:
function svc = svc_com pletion(d, pe_sig)
%#eml
%SVC_COMPLETION Output 1 upon each service comple tion.
% SVC = SVC_COMPLETION(D, PE_SIG) outputs 1 if output signals from a
% server block indicate that a service completion occurred. The function
% outputs 0 otherwise. D is the #d output signal from a server block.
% PE_SIG is the #pe output signal from an N-Server or Infinite Server
% block, or the pe output signal from a Single Server block.
% Declare variables tha t must retain values between iterations.
persistent last_d last_pe_sig;
% Initialize persistent variables in the first iteration.
if isempty(last_d)
last_d = 0;
last_pe_sig = 0;
end
2-24
% Compute the output. A service completion occurred if either is true:
% * d increases and pe_sig remains the same.
% * pe_sig increases.
if ((d > last_d && isequal(pe_sig,last_pe_sig)) | | (pe_sig > last_pe_sig))
svc = 1;
else
svc = 0;
end
% Update the persistent variables for the next iteration.
last_d = d;
last_pe_sig = pe_sig;
Observing Events
Note The subsystem does not execute upon decreases in #pe. A decrease in #pe means that a pending entity has departed. The departure causes a simultaneous increase in #d, but the block updates #pe before #d.Executing the subsystem upon decreases in #pe wouldbeincompatiblewiththe preceding code because #pe would reflect the departure but #d would not.
The output signal from the subsystem, svc, has a sample time hit of 1 whenever there is a service completion. The signal also has sample time hits of 0 w hen the subsystem executes but there is no service completion. To removethesampletimehitsof0,theexampleconnectsthe ts and e1 input ports of the Signal-Based Event to Function-Call Event block. Each time a service completion occurs, the block:
Generates a function call at the f1 output port
Increases the value of the #f1 output signal
svc signal to the

Example: Detecting Collisions by Comparing Events

The e xample below a ims to determ ine whether an entity is the only entity in an infinite server for the entire duration of service. The model uses the Signal Latch block to compare the times of two kinds of events and report which kind occurred more recently. This usage of the Signal Latch block relies on the block’sstatusoutputsignal,st, rather than the default in and out ports.
2-25
2 Working with Events
In the mode l, entities arrive at an infinite server, whose #n output signal indicates how many entities are in the server. The Signal Latch block responds to these signal-based events involving the integer-valued #n signal:
2-26
Observing Events
If #n increas es from 0 to a larger integer, then
- rtr has a rising edge.
- The Signal Latch block processes a read event.
- The Signal Latch block’s st output signal becomes 0.
If #n increas es from 1 to a larger integer, then
- wtr has a rising edge.
- The Signal Latch block processes a write event.
- The Signal Latch block’s st output signal becomes 1.
If #n increases from 0 to 2 at the same value of the simulation clock, then it
also assumes the value 1 as a zero-duration value. As a result,
- rtr and wtr both have rising edges, in that sequence.
- The Signal Latch block processes a read event followed by a write event.
- The Signal Latch block’s st output signal becomes 1.
By the time the entity departs from the Infinite Server block, the Signal Latch block’s st signal is 0 if and only if that entity has been the only entity in the server block for the entire duration of service. This outcome is considered a success for that entity. Other outcomes are considered collisions between that entity and one or more other entities.
This example is similar to the CSMA/CD subsystem in the Ethernet Local Area Network demo.
2-27
2 Working with Events

Generating Function-Call Events

In this section...
“Role of Explicitly Generated E vents” on page 2-28
“Generating Events When Other Events Occur” on page 2-28
“Generating Events Using Intergeneration Times” on page 2-30

Role of Explicitly Generated Events

You can generate an event and use it to
Invoke a discrete event subsystem, Embedded MATLAB Function block, or
Stateflow block
Cause certain events, such as the opening of a gate or the reading of
memory in a Signal Latch block
Generate an entity
2-28
For m ost purposes, a function call is an appropriate type of event to generate.
Note While you can invoke trigge red subsystems,Embedded MATLAB Function blocks, and Stateflow blocks upon trigger edges, trigger usage has limitations in discrete-event simulations. In particular, you should use function calls instead of triggers if you want the invocations to occur asynchronously, to be prioritized among other simultaneous even ts , or to occurmorethanonceinafixedtimeinstant.

Generating Events When Other Events Occur

The table below indicates which blocks generate function calls when other events occur.
Generating Function-Call Events
Event Upo n Which to Generate Another Event
Entity advancement
Signal-based event Signal-Based Function-Call Event Generator
Function call
Block
Entity-Based Function-Call Event Generator
Signal-Based Function-Call Event Generator
Example: Calling a Stateflow Block Upon Changes i n Server Contents
The fragment below, which is part of an example in “Using Stateflow Charts to Implement a Failure State” on pag e 5-21, uses entities to represent failures and repairs of a server elsewhere in the model:
A failure of the server is modeled as an entity’s arrival at the block labeled
Repair Work. When the Repair Work block’s #n signal increases to reflect the e ntity arrival, the Signal-Based Function-Call Event Generator block generates a function call that calls the Stateflow block to change the state of the server from up to down.
A completed repair of the server is modeled as an entity’s departure from
the Repair Work b lock. When the Repair Work block’s #n signal decreases to reflect the entity departure, the Signal-Based Function-Call Event Generator block generates a function call that calls the Stateflow block to change the state of the server from down to up.
2-29
2 Working with Events
One reason to use function calls rather than triggers to call a Stateflow block in discrete-event simulations is that an event-based signal can experience a trigger edge due to a zero-duration value that a time-based block would not recognize. T he Signal-Based Function-Call Event Generator can detect signal-based events that involve zero-duration values.

Generating Events Using Intergeneration Times

To generate events using intergeneration times from a signal or a statistical distribution, use this procedure:
1 Use the signal or statistical distribution with the Time-Based Entity
Generator block to generate entities.
2 Use the Entity-Based Function-Call Event Generator block to generate an
event associated with each entity.
3 Terminate the entity path w ith an Entity Sink block.
In the special case when the intergeneration time is constant, a simpler alternative is to use the Function-Call Generator block in the Simulink Ports & Subsystems library.
2-30
Example: Opening a Gate Upon Random Events
The example below uses the top entity generator to generate entities whose solepurposeistocausethegenerationof events with intergeneration times from a statistical distribution. The bottom entity generator generates entities that enter a gated queuing system.
Generating Function-Call Events
2-31
2 Working with Events

Manipulating Events

In this section...
“Reasons to Manipulate Events” on page 2-32
“Blocks for Manipula ting Events” on page 2-34
“Creating a Union of Multiple Events” on page 2-34
“Translating Events to Control the Processing Sequence” on page 2-37
“Conditionalizing Events” on page 2-39

Reasons to Manipulate Events

You can manipulate events to accomplish any of these goals:
To invoke a function-call subsystem, Embedded MATLAB Function block,
or Stateflow block upon entity departures or signal-based events.
2-32
Note You can invoke triggered subsystems, Embedded MATLAB Function blocks, and Stateflow blocks upon trigger edge s, which are a type of signal-based event. However, you will need to translate the trigger edges into function calls if you want the invocations to occur asynchronously, to be prioritized among other simultaneous events, or to occur more than once in a fixed time instant.
To create a union of events from multiple sources. See “Creating a Union
of Multiple Events” on page 2-34.
To prioritize the reaction to one event relative to other simultaneous events.
See “Translating Events to Control the Processing Sequence” on page 2 -37.
To delay the reactions to events. See the Function-call time delay
parameter on the Signal-Based Event to Function-Call E vent blocks reference page.
To conditionalize the reactions to events. See “Conditionalizing Events”
on page 2-39.
Manipulating Events
The term event translation refers to the conversion o f one event into another. The result of the translation is often a function call, but can be another type of event. The result o f the translation can occur at the same time as, or a later time than, the original event.
2-33
2 Working with Events

Blocks for Manipulating Events

The table below lists blocks that are useful for manipulating events.
Event to Manipulate
Entity advancement
Signal-based event Signal-Based Event to Function-Call Event
Function call
If you connect the Entity D eparture Counter blo ck’s #d output port to a block that detects sample time hits or rising value changes, then you can view the counter as a mechanism for converting an entity advancement event into a signal-based e vent. Corresponding to each entity departure from the block is an increase in the value of the #d signal.
Block
Entity Departure Event to Function-Call Event
Signal-Based Event to Function-Call Event
Mux

Creating a Union of Multiple Events

To generate a function-call signal that represents the union (logical OR) of multiple events, use this procedure:
1 Generate a function call for each event that is not already a function call.
Use blocks in the Event Generators or Event Translation library.
2 Use the Mux block to combine the function-call signals.
2-34
The multiplexed signal carries a function call when any of the individual function-call signals carries a function call. If two individual signals carry a function call at the same time instant, then the multiplexed signal carries two function calls at that time instant.
Examples are in “Example: Performing a Computation on Selected Entity Paths” on page 10-31 and below.
Manipulating Events
Example: Counting Events from Multiple Sources
The example below illustrates different approaches to event translation and event generation. This example varies the approach for illustrative purposes; in your own models, you might decide to use a single approach that you find most intuitive.
The g oal of the example is to plot the number of arrivals at a bank of three servers at each value of time. Entities advance to the servers via one or two FIFO Queue blocks. To count arrivals and create the plot, the model translates each arrival at a server into a function call; the Mux block combines the three function-call signals to create an input to the Instantaneous Event Counting Scope block.
The three server paths use these methods for translating an entity arrival into a function call:
One path uses the Entity Departure Event to Function-Call Event block,
treating the problem as one of event translation.
One path uses the Entity-Based Event Generator block, treating the
problem as one of event generation. This is similar to the approach above.
One path uses the Signal-B ased Event to Function-Call Event block to
translate an increase in the value of the server block’s #n signal into a function call. This approach uses the fact that each arrival at the server block causes a simultaneous increase in the block’s #n signal.
2-35
2 Working with Events
2-36
Manipulating Events
Example: Executing a Subsystem Based on Multiple Types of Events
You can configure a Discrete Event Subsystem block to detect signal-based events from one or more sources, and you can configure a Function-Call Subsystem b lock to detect function calls from one or more s ources. Using an event translation block to convert a signal-b ased event into a function call, the fragment below effectively creates a subsystem that detects a function call from a Stateflow block and a signal-based event from another source. The subsystem is executed when either the Stateflow block generates a function call or the signal connected to the vc port of the Signal-Based Event to Function-Call Event block changes. If both events occur simultaneously, then the subsystem executes twice.
“Block execution” in this documentation is shorthand for “block methods execution.” Methods are functions that the Simulink engine uses to solve a model. Blocks are made up of multiple methods. For details, see “B lock Methods” in the Simulink documentation.
er similar example is in “Example:PerformingaComputationon
Anoth
ted Entity Paths” on page 10-31.
Selec
slating Events to Control the Processing Sequence
Tran
me situations, event translation blocks can help you prescribe the
In so
cessing sequence for simultaneous events. The examples below illustrate
pro
to do this by taking advantage of the sequence in which an event
how
nslation block issues two function calls, and by converting an unprioritized
tra
ction call into a function call having an event priority.
fun
2-37
2 Working with Events
Example: Issuing Two Function Calls in Sequence
In the next model, entity generation and the execution of a function-call subsystem can occur simultaneously. At such times, it is important that the entity generation occur first, so that the entity generator u pdates the value of the w signal before the function-call subsystem uses w in its computation. This model ensures a correct processing sequence by using the same Signal-Based Event to Function-Call Event block to issue both function calls and by relying on the fact that the block always issues the f1 function call before the f2 function call.
In this example, the Signal-Based Event to Function-Call Event block has this configuration:
2-38
Generate function call only upon =
Generate optional f2 function call selected
In this example, the Function-Call Split block in the Simulink libraries is not an alternative because it cannot connect to SimEvents blocks.
Function call from port fc n
Example: Generating a Function Call with an Event Priority
The next model uses an ev ent translation block to prioritize the execution of a function-call subsystem correctly on the event calendar, relative to a simultaneous event. In the model, a Stateflow block and an entity generator respondtoedgesofthesametriggersignal. The Stateflow block calls an event translation block, which in turn calls a function-call subsystem. The subsystem perform s a computation using the w output signal from the entity generator.
Manipulating Events
As in the earlier example, it is important that the entity generator update the value of the w signal before the function-call subsystem uses w in its computation. To ensure a correct processing s equence, the Signal-Bas ed Event to Function-Call Event block replaces the original function call, which is not scheduled on the event calendar, with a new function call that is scheduled on the event calendar with a priority of 200. The Event-Based Entity Generator block schedules an entity-generation event on the eve nt calendar with a priority of 100. A s a result of the event translation and the relative event priorities, the entity generator generates the entity before the event translator issues the function call to the function-call subsystem whenever these events occur at the same value (or sufficiently close values) of the simulation clock.

Conditionalizing Events

The Entity Departure Event to Function-Call Event and Signal-Based Event to Function-Call Event blocks provide a way to suppress the output function call based on a control signal. If the control signal is zero or negative when the block is about to issue the function call, then the block suppresses the function call. You can use this feature to
Prevent simulation problems. The example in “Example: Detecting
Changes in the Last-Updated Signal” on page 16-35 uses conditional function calls to prevent division-by-zero warnings.
Model an inoperative state of a component of your system. See the next
example.
2-39
2 Working with Events
Example: Modeling Periodic Shutdown of an Entity Generator
The example be low uses Event-Based Entity Generator blocks to generate entities when a pulse signal changes its value. The top entity generator generatesanentityuponeachsuchevent. The bottom entity generator responds to a function call issued by an event translation block that detects changes in the pulse signal’s value. However, the e ve nt translation block issues a function call only upon value changes that occur while the e1 input signal is positive. In this model, a nonpositive value of the e1 signal corresponds to a failure or resting period of the entity generator.
2-40

Managing Simultaneous Events

“Overview of Simultaneous Events” on page 3-2
“Exploring Simultaneous Events” on page 3-4
“Choosing an Approach for Simultaneous Events” on page 3-7
“Assigning Event Priorities” on page 3-8
“Example: Choices of Values for Event Priorities” on page 3-11
3
“Example: Effects of Specifying Event Priorities” on page 3-26
3 Managing Simultaneous Events

Overview of Simultaneous Events

During a simulation, multiple events can occur at the same value of the simulation clock, whether or not due to causality. Also, the application treats events as simultaneous if their event times are sufficiently close, even if the event times are not identical. Events scheduled on the event calendar for times T and T+Δt are considered simultaneous if 0 ≤Δt
eps is the floating-point relative accuracy in MATLAB software and T is
the simulation time.
This table indicates sources of relevant information that can help y ou understand and manage simultaneous events.
128*eps*T,where
To Rea d About...
Background
Behavior
Examples
Tips
Techniques
Refer to...
“Supported Events in SimEvents Models” on page 2-2
“Event Sequencing” on page 16-2
“Example: Event Calendar Usage for a Queue-Server Model” on page 2-10
“Example: Choices of Values for Event P riorities” on page 3-11
“Example: Effects of Specifying Event P riorities” on page 3-26
“Choosing an Approach for Simultaneous Events” on page 3-7 and “Tips for Choosing Event Priority Values” on page 3-8
“Exploring Simultaneous Events” on page 3-4 and “Assigning Event Priorities” on page 3-8
Description
Overview of event types and the event calendar
How the application determines which events to process first, when time and causality alone do not specify a unique sequence
Illustrates basic functionality of the event calendar
Examinestheroleofeventpriority values
Compares simulation behaviors when you specify and do not specify event priorities
Tips to help you decide how to configure your model
Viewing behavior and working with explicit event priorities
3-2
Overview of Simultaneous Events
When one of the simultaneous events is a signal update, information in “Choosing How to Resolve Simultaneous Signal Updates” on page 16-7 is also relevant.
3-3
3 Managing Simultaneous Events

Exploring Simultaneous Events

In this section...
“Using Nearby Breakpoints to Focus on a Particular Time” on page 3-5
“For Further Information” on page 3-5
One way that you can see details about which events occur simultaneously and the sequence in which the application processes them is by running the simulation with the SimEvents debugger. The debugger displays messages in the Command Window to indicate what is happening in the simulation, and lets you inspect states at any point where the debugger suspends the simulation. You might still need to infer some aspects of the simulation behavior that do not appear in the Command Window messages.
Tips for how you can use the debugger to explore simultaneous events, where the commands mentioned are valid at the are:
sedebug>> prompt of the debugger,
3-4
If you want to view the event calendar at any point in the simulation,
enter
evcal.
If all the events you w ant to explore are on the event calendar and you are
not interested in entity operations, enter log no longer issues messages about entity operations and the ignores entity operations.
The opposite command is log to include messages about entity operatio ns and makes it possible f or
step to suspend the simulation at an entity operation.
If you want to see everything that happens at a particular time, use a
pair of timed breakpoints, as in “Using Nearby Breakpoints to Focus on a Particular Time” on page 3-5.
If you want to proceed in the simulation until it executes or cancels a
particulareventthatisontheeventcalendar, find the e ve nt identifier (using command, and then enter cont.
An event breakpoint is not the same as a timed breakpoint whose value
equals the scheduled time of the event. The two breakpoints can cause
evcal or the simulation log), use the event identifier in an evbreak
detail('en',1), which causes the simulation
detail('en',0).Thesimulation
step function
Loading...