Size: px
Start display at page:

Download ""

Transcription

1 ENGM 541, ENGM 670 & MECE 758 Modeling and Simulation of Engineering Systems Winter 2011 Lecture 9: Discrete Event Systems Modeling & Simulation M.G. Lipsett University of Alberta Review of Mixed Systems In a propagation problem, elements can store, release, or dissipate energy over time. Instantaneously, the power in does not necessarily equal power out (where power is the product of effort and flow) A-type element: energy equation is written in terms of Across variable (kinetic energy, electrical potential, etc.) T-type element: energy equation is written in terms of Through variable (mech potential energy, inductance, etc.) D-type element: Dissipates energy (damper, resistor, etc.) Energy storage and dissipation devices are one-port devices. They accept an effort or flow as input, and they output the complementary effort or flow MG Lipsett,

2 Review of Mixed Systems (2) Transducers & Transformers are two-port devices. They always interconnect two effort/flow pairs Transducers convert between different types of power (power being provided at the driver side, power going into the system at the driven side) Amplifiers and modulators are three-port devices, with control input and power ports Subsystems connect through transducers that transform energy (sensors and actuators) Descriptions of subsystems and connections form the overall equations of motion We analyse each subsystem, then transform variables at the transforming elements (which typically have a well defined constitutive relationship) MG Lipsett, Discrete-Event Systems Until now, we have considered continuous systems, in which variables are functions of continuous time and have a continuous range of values (also called analog systems), related by constitutive relationships based on physics The state trajectory is the solution of In many engineering systems, however, the behaviour can be described without having to model the underlying physics. This is done by defining a finite set of discrete states and the conditions by which they change. Activities in information technologies (digital computers, networks, ) Activities in projects, manufacturing, and services Changes in state occur discontinuously In time & in the number of allowable states (finite states) MG Lipsett,

3 General Modeling of Discrete-Event Systems Inputs - finite number of defined states Processing - wait or hold until conditions are satisfied Outputs (when conditions met) finite number of states clock Time (k) input state 1 input state 2 input state 3 input state 4 input state 5 input state N conditions process Time (k+1) output state 1 output state 2 output state 3 output state 4 output state 5 The conditions for the process define the constitutive relationship between the inputs and outputs output state N MG Lipsett, Finite State Machine model of behavior composed of: finite number of states transitions between those states, and actions A current state is determined by past states of the system. thus it records information about the past, reflecting the input changes from the system at the start to the present moment. A transition indicates a state change described by a condition that would need to be fulfilled to enable the transition An action is a description of an activity that is to be performed at a given moment MG Lipsett,

4 Action Types Entry action which is performed when entering the state Exit action which is performed when exiting the state Input action which is performed depending on present state and input conditions Transition action which is performed when performing a certain transition Acceptors and recognizers (also sequence detectors) produce a binary output, saying either yes or no to answer whether the input is accepted by the machine or not. A all states of this kind of FSM are either accepting or not accepting Transducers generate output based on a given input and/or a state using actions. Two types: output depends only on the state (Moore machine) output depends on input and state (Mealy machine) Transaction action (condition) MG Lipsett, Example: Sequence Detector (Moore Graph) S 0 0 S 1 0 S 3 1 S 2 0 MG Lipsett,

5 Discrete-Event Modeling of Manufacturing Manufacturing naturally divides into discrete activities Receiving batches of raw material Material handling of pallets with batches of intermediate product Specific actions: Cutting, drilling, milling, turning, welding, forging, injection molding, grinding, inspection, packaging, shipping, etc., etc. transport set-up tool change mill tool change drill tool change tap inspect Source: en.wikipedia.org/wiki/industrial_robot MG Lipsett, Manufacturing Process Analysis Analysis of manufacturing activities is done for a number of reasons Product design (designing for manufacturability) Plant design (to ensure that each process step is included and that specifications match throughout the process, including throughput) Operations management (to eliminate bottlenecks that limit production, reduce inventory without creating bottlenecks, and to improve efficiency and profitability) Scheduling activities so that resources are not idle (or overcommitted) Activity-Based Costing is a modern accounting method that tracks cost as one of the state variables, allowing money to be tracked as a resource (or hopefully an output) MG Lipsett,

6 General Algorithm The main loop of a discrete-event simulation is something like this: Start Initialize Ending Condition to FALSE. Initialize system state variables. Initialize Clock (usually starts at simulation time zero). Schedule an initial event (i.e., put some initial event into the Events List). Do loop or While loop While (Ending Condition is FALSE) then do the following: Set clock to next event time. Do next event and remove from the Events List. Update statistics. End Generate statistical report. MG Lipsett, MG Lipsett, Components of a Discrete-Event Simulation Clock keeps track of current time in the simulation. Important because time steps are not controlled by the solver, but rather are dictated by the events. Time advances to the next event start time. Events List Minimum of one list of simulation events that have yet to be simulated (also called the pending event set). Event description includes time of occurrence and its event type, which specifies the formulation used for simulating that event (usually including related parameters). Events can be instantaneous, in which case activities with durations are sequences of events. (In some DES, event is specified as an interval, with start and end time.) Single-threaded simulators for instantaneous events have only one current event. Multi-threaded simulators and simulators using interval-based event models can have more than one current event. (Synchronization between current events can be a problem, dealt with using a priority queue to sort the pending event set, and dynamic scheduling of events while the simulation runs.) Pseudo-Random-Number Generators Used to generate inputs or conditions when the simulation is non-deterministic (Monte Carlo). Archival Statistics Keeps track of inputs and outputs of interest, such as throughput, reject rate, number of times certain activities occur, etc. Ending Condition Determines when to stop the simulation, usually after some time is reached, or some number of events has occurred, or when some statistical measure reaches a particular value. 6

7 Synchronous and Asynchronous Models In a synchronous model, all of the activities go by the same clock, and transitions all occur at once In an asynchronous model, transitions can occur at different times MG Lipsett, General Structured Analysis Before constructing a computer simulation, a process has to be analysed, to understand what all of the events are, how they work, and how they connect Similar to setting up a set of governing equations Approaches include: event-based, activity-based, processbased and three-phase Essentially structured methods for creating flowcharts for stepwise processes (such as computer code execution) including decision choices, iteration, and possibly concurrency Methods include Activity diagram (Universal Markup Language) Business Process Modelling Notation (BPMN) Event-driven Process Chain (EPC) Petri Net MG Lipsett,

8 Petri Net A modeling language for describing discrete distributed systems Consists of places (condition nodes), transitions (event nodes), and directed arcs (joining arrows). Transitions are event nodes (discrete events) signified by bars Places are condition nodes (resources) signified by circles Directed arcs, signified by arrows, connect precondition &/or postcondition to transitions A Petri Net is a directed bipartite graph (every arc connects places and transitions) A system is modeled with two sets of nodes: a set of "place" nodes that contain resources, and a set of "event" nodes which generate and/or consume resources. Constraints on the nodes and edges (arcs) determine the system behavior. MG Lipsett, Modeling for Discrete-Event Simulations Each process is connected in sequence Output state from the preceding process must link to the input state for the next process A process may be a branching condition, where the input state causes the output to route to one of a number of possible downstream processes The branching condition may be implemented in two ways: automatically within the system itself using embedded logic, or human decision MG Lipsett,

9 Modeling States The overall model must include ways in which all of the states of interest can change Each activity block has to receive input states, and have outputs for the possible changes in states Resources Input state Activity Output state(s) Conditions for transition (activity completion) MG Lipsett, Modeling Conditions for State Transitions Logical conditions are described for each activity block The logical conditions are based on the states, and may also be based on the time &/or external inputs to the system. State transitions are result of some activity. From an activity block of interest, the output vector of states appears as the input to any activity block connected to the output of the block. The time at which the state transition occurred may be tracked (as a system performance measure). MG Lipsett,

10 Forming System Models from Elements DES packages allow modelers to construct models from sets of elements, producing a network of connected elements, allowing for inputs to the system, keeping track of variables and performance measures as the simulation progresses, and displaying results. Graphical user interfaces are convenient for laying out the sequence of activities, the connections between activities, defining related events, and debugging MG Lipsett, General Structured Analysis of an Activity Block Connected network of blocks Discrete-event Variables Constraints & conditions Process activities Information & resources Outputs MG Lipsett, Events cause something to happen 10

11 Producing a Discrete-Event Simulation To produce a DES, additional information is necessary beyond the sequence of activities and branching decisions: Descriptions of conditions when events happen, such as a change in a state variable or elapsed time, which cause an activity (or a decision) to occur Information that describes the activity (which we can think of as the constitutive relationship or a process), its constraints, any decision variables, etc. Resources necessary for a particular activity to occur (these may also act as constraints) Description of conditions that determine when the activity ends Outputs of each activity (and which particular outputs relate to important performance measures for the system) Initialisation and termination criteria MG Lipsett, Universal Markup Language Format The UML format for a State-Flow diagram uses the following convention: Rounded rectangles represent activities; Diamonds represent decisions; Bars represent the start (split) or end (join) of concurrent activities; A black circle represents the start (initial state) of the workflow; An encircled black circle represents the end (final state). Arrows run from the start towards the end and represent the order in which activities happen; Squares connecting to activity blocks represent resources and information required for the activity. MG Lipsett,

12 In-Class Example: Describe An Activity MG Lipsett, Example: Warehouse Receiving Flowchart of activities involved in receiving material at the loading bay of a warehouse (Not quite UML format) MG Lipsett,

13 Model Verification A reality check to test whether the model is appropriate Have someone else check the narrative of the model Test the model under known conditions where you know what to expect from the system (e.g. benchmark cases) Appropriate inputs (including distributions for random inputs) Known outputs (like boundary conditions on a stress analysis) Verification is not the same as validation Validation is confirmation that you are simulating the system of interest correctly with a sufficiently accurate model MG Lipsett, Example: Robotic Mining Excavation A shovel basically does only two things: it digs dirt, and it moves to where it digs more dirt. The tasks involved to dig dirt are: 1. Collect geometric data from the local environment 2. Collect internal sensor data on the status of the machine 3. Generate the workspace model of relative location of shovel to ore face and to goal location (truck) 4. Get the desired task criterion (ore grade) 5. Choose the goal location for dumping in the truck 6. Choose a location in the ore face for digging that is within specification 7. Plan a collision-free move to the digging location MG Lipsett,

14 Example: Robotic Mining Excavation (2) 8. Move along the path to the digging location 9. Execute a digging action (appropriate to the ore type) to break material and fill the bucket 10.Plan a collision-free path from the pose at the end of the digging action to the dump position (truck) 11.Execute the move to the dump position 12.Dump the material (open the bucket door, or tilt the bucket) 13. Wait for the bucket to empty 14.Close the bucket door (or tilt the bucket to ready position) 15.Wait for input to start a new sequence MG Lipsett, Example: Robotic Mining Excavation (3) Start Mission Script Execution Determine next dig location Position scoop over dig location Discrete-event task planning with automatic execution (details of digging action; other sensing and status checks not shown) Rotate scoop to point teeth down Penetrate soil to 6 inch depth Rotate Elbow to cut desired trench length at 6" depth Rotate scoop and lift arm (remove soil) Position digging tool over dump location Timeout* Rotate Elbow to cut desired trench length at shallower depth Rotate scoop and lift arm (remove soil) No Elbow progress, or Loop Count Limit Reached (* ie Goal position could not be reached within timeout period, prolonged motor stall condition, tilt limit or force limit is exceeded) Timeout Slightly rotate scoop back/forth (loosen soil) Rotate Elbow to cut desired trench length Rotate scoop and lift arm (remove soil) Timeout (Execute this loop while it facilitates elbow motion, or apply loop count limit) Rotate tool to dump soil MG Lipsett,

15 Using Software To Develop a DES There are many structured analysis programs that can be used for structured analysis Even a spreadsheet such as Excel can be used to generate a DES MATLAB has an add-on to SIMULINK called SIMEVENTS, for discrete-event modeling & simulations The advantage of this add-on is that within one framework you can also create hybrid models A hybrid model combines continuous and discrete systems An example of a hybrid system is a continuous process (described by differential equations) combined with a batch process (described by events) MG Lipsett, A Simple Framework for a DES No matter what approach we take to develop a DES, it will have the following aspects: Set-up of the model Conditions associated with each activity Actions triggered by events Connections between activities & events Initialisation of initial states Running of the simulation Tracking of variables Generation of some kind of output report MG Lipsett,

16 Designing Systems Using DES Simulation is a powerful technique for design, allowing us to predict how a system will perform even before it is built, including: Feasibility of a Sequence Outcomes of Scenarios Duration of a Sequence Variability Product quality System reliability Revenues and Costs Energy Consumption Allocation of Resources to a Network Power distribution Fleet assignments Allocation of Resources over Time Scheduling MG Lipsett, Modeling Variability: Monte Carlo Simulation Up to now, our solutions have been the answer But often we have uncertainty in our understanding of the inputs to a system (or aspects of the system itself!) Monte Carlo simulation is a probabilistic analysis of a system Inputs are probabilities (distributions or functions) Process is the system model Output is the system response (or analysis result), Output Inputs Process Solution must be robust to the bandwidth of the inputs MG Lipsett,

17 Monte Carlo Method for Forecasting Forecasting is prediction with uncertainty Initialise variables & time Increment time Done? Generate r.v. Pick variable values from distributions Use dynamic model to calculate new state A time-driven Monte Carlo simulation steps through increments of time, just like our propagation simulations for solving ODEs Calculate outputs Archive outputs MG Lipsett, Event-Driven Monte Carlo Simulation (3) MG Lipsett, An event-driven Monte Carlo simulation is structurally different from a time-driven Monte Carlo simulation Time is not discretised All elements of the system are checked at the beginning of the simulation, and event times are computed for each using probability distributions Starting from time t=0, the time of the first event is found The clock moves to that time t, and states and outputs are calculated and stored Based on the new current state, the times of the next set of future event times is calculated using probability distributions The event with the shortest incremental time is chosen, and the clock moves to that time for the next event 17

18 Examples of Probability Distribution Functions Exponential Gaussian Discrete RVs (e.g. sampled data) have discrete PDFs Uniform Beta Gamma PDFs can be Multidimensional Weibull Many others MG Lipsett, Estimating Probability Distributions Distributions are based on data: Actuarial data (other systems) Empirical data (plant data, experiment) Probabilistic transformations from other PDFs through a system model (using a Jacobian function) The MATLAB Statistics Toolbox can find the best fit of a number of different types of PDFs to a data set (including combinations) For example, normfit finds the best-fit estimate for a normal (Gaussian) distribution: [muhat,sigmahat] = normfit(data) returning estimates of the mean µ and standard deviation σ of the normal distribution, given the data in the array data MG Lipsett,

19 Non-Physics Physics-Based Models of Systems Discrete-Event Systems Finite-state machines Simplified representations of activities Dynamics modeled simply as state transitions Manufacturing and other processes More generally, we can model system processes such as: Resource Allocation Scheduling & Inventory Financial transactions Organisational Behaviour MG Lipsett, Resource Allocation An equilibrium solution for a system Assigning parameters to the elements of a system to achieve a steady-state specification Usually in the context of assigning resources Examples: Selecting power supplies for an electrical circuit Assigning a number of machines to produce widgets in a factory Assigning a number of mining trucks to move ore on a network of haul roads Picking people for a team to do a task MG Lipsett,

20 Scheduling A sequence of tasks is scheduled so that they are executed in proper order, with prerequisite activities completed first A variety of search methods are used to find feasible (hopefully optimal) schedules A priority list Source: MG Lipsett, Scheduling Method 1: Forward to Goal Forward scheduling plans the tasks from the date that resources become available to determine the shipping date or the due date. MG Lipsett,

21 Scheduling Method 2: Backward from Goal Backward scheduling plans the tasks from the due date or required-by date to determine the start date and/or any changes in capacity required Companies use backward and forward scheduling to allocate plant and machinery resources, plan human resources, plan production processes and purchase materials. MG Lipsett, Scheduling Method 3: Heuristics Production scheduling can take a significant amount of computing power if there are a large number of tasks. Short-cut algorithms or heuristics are used to reduce time and get a good enough solution Short term scheduling methods can be classified according to: selection criterion they use to decide which process, among the ready ones, should be executed next, and decision mode used to determine when the process switch is to take place Dispatcher may be human or algorithm MG Lipsett,

22 Heuristics (2) Selection criteria examples: First come, first served Round robin Shortest process next Shortest remaining time next Most valuable process next Decision modes can be either pre-emptive or non-preemptive (or co-operative) Pre-emptive: a running process may be blocked by the dispatcher because of the scheduling policy used Examples: expiration of a fixed time slice, submission of a process with higher priority, or occurrence of other allowable interruption Non-pre-emptive: a running process is given control until completion MG Lipsett, Critical Path Method (CPM) Plan the work, then work the plan. Carrying out all the activities in order Keeping on schedule means putting extra effort into activities that are on the critical path Activity A Activity B Activity C Activity D Activity E Time While ensuring safety & quality of work And ensuring that all other key conditions of success are met MG Lipsett,

23 Critical Path Example For parallel sequences of activities: The sequence with the longest duration is the critical path Activity R: $16k Duration 6 days Activity S: $8k Duration 5 days Activity T: $4k Activity V: $1k Duration 2 days Activity W: $3k Duration 4 days Duration 3 days Activity X: $5k Duration 3 days Activity U: $11k Duration 14 days This is where delay in an activity would delay the whole project MG Lipsett, Inventory Inventory is the ordering, receiving, handling, and shipping of raw material, intermediate product, and finished goods for a process Modeled as flows of material between elements In a perfect world, all activities would work smoothly and the output from one discrete activity (or continuous process) would match the input requirements of the downstream activity (or process) In reality, there is always variability (stuff happens) Excessive variability can drive a system unstable Some inventory must be held between processes to dampen out the natural variability and provide a buffer of material Pallets of partially finished goods, tanks of intermediate product, etc. Inventory is expensive (it s an asset that doesn t earn any income until it s actually sold) Companies put a lot of effort into minimising inventory while maintaining stable operational control (Just In Time manufacturing holds inventory in trucks rather than warehouses) Supply chain management is critical to a company s survival MG Lipsett,

24 Services Companies that provide services (such as call centres) also analyse their activities to find efficiencies Service models are also commonly used for information networks (which makes sense because a service involves information rather than physical goods). Two types: an exchange of information (query, search, sort, update, communicate); or an information transaction that changes the information (decision, authorisation, etc.) Source: /keller geo_vis_services /images/fig4_web_service_model.jpg MG Lipsett, Supply Chain Dynamics A supply chain models the complete sets of sources and movements of materials and services that an organization relies on for its own production. Companies rely greatly on having a predictable supply of materials (and services of people) to conduct its business. The supply chain responds dynamically to the availability of supply, demands of the user/customer, and the vagaries of transporting to get goods from supplier to user on time and on budget. In its simplest (equilibrium) form, a supply chain is a set of connected suppliers, who take in material (raw or partially processed) and process it in some way, such as assembly or transportation, before sending it on to the next element in the supply chain. MG Lipsett,

25 Supply Chain (2) Supply chain simulation helps planners and procurement managers to understand how a supply chain can deal with a set of conditions that may affect getting the product you need to satisfy your customers. There are two key challenges in supply chain management: First, make sure that none of the links in the chains is broken, such as a supplier who has no product, or a transport company that has no trucks available. Second, make sure that each link is strong enough. To get the throughput required, each link in the supply chain has to have at a minimum the capacity to deliver the required throughput. The weakest link is the one with the lowest capacity. This is where a bottleneck will occur. MG Lipsett, Supply Chain (3) Process 1 can provide a units per hour of material A Process 2 can provide b units per hour of material B (etc.) The supply chain gets interesting when processes depend on the input rate or the output rate. For example, Process 3 can provide c units per hour of material C as an output, but in order to produce one unit of C, Process C must have 4 units of A and 1 unit of B. This means that in this simple system, Process B is the bottleneck that continually limits production of product. MG Lipsett,

26 Supply Chain (4) For linear, steady-state process relationships, linear programming can be used to solve for the maximum throughput rate, and to find the constraint that limits production. This is an equilibrium solution. Supply chains gets really interesting when there are dynamic relationships that affect the throughput rates of different process elements, especially when there are nonlinearities. We can use an analogy to continuous flow: Production demand drives the system (like a source) Response to demand by a supplier affects the flow of supply (like voltage across an inductor affects rate of change of current) Inventory tends to accumulate (like a capacitor accumulates charge) Inefficiencies in the system dampen system performance (like a resistor dissipates energy: inefficiencies dissipate profit) MG Lipsett, Continuous & Discrete Supply Chain Models While most goods are transported as pieces, the dynamics of a supply chain can often be modeled as a simple continuous system. Nonlinear elements can be introduced relating demand p (effort loop variable) to supply (flow rate node variable) q : Limited inventory capacity Q I Limited ability to respond to changes in flow rate: q. MG Lipsett,

27 Find the Bottleneck A bottleneck is a restriction in the range of response through an element (usually the node variable) This makes this element of the system nonlinear. You want to focus on the bottleneck and remove the restriction on flow for a given demand; but remember what Wayne Gretzky said: don t go where the puck is - go where the puck will be. In other words, don t chase bottlenecks, but anticipate where they may occur, so that you can deal with bottlenecks pro-actively and effectively to maintain the required throughput. MG Lipsett, SUMMARY MG Lipsett, Many systems are best described in discrete event rather than evolution of continuous variables Discrete-event systems can have dynamic behaviour, just like continuous systems Discrete-event simulations emulate this behaviour by keeping track of how discrete states change after events occur due to activities spawned by the event SIMULINK has a library of blocks to model activities and the input-output relationships (static or dynamic) MATLAB & SIMULINK can convert between discrete and continuous representations (In this way a continuous representation can be converted to its discrete equivalent, assuming equal discretisation intervals) An add-on package for SIMULINK called SIMEVENTS is used for discrete-event simulations & hybrid-system simulations 27

28 Alan Turing The Turing Machine: Intuitively a task is computable if one can specify a sequence of instructions which when followed will result in the completion of the task. Such a set of instructions is called an effective procedure, or algorithm, for the task. Mathematician Alan Turing proposed a class of devices that came to be known as Turing machines. Turing machines are not physical objects but mathematical ones. The Turing Test: A human judge engages in a natural language conversation with one human and one machine, each of which tries to appear human. If the judge cannot reliably tell the machine from the human, the machine is said to have passed the test. Sources: MG Lipsett,