A tutorial on how to use the Flexsim Simulation Software....
Flexsim Tutorial
Bill KP Chan HW 1-6 Email:
[email protected]
Flexs im Con cept s & T erm in ol og y • Model • Objects - Fixed Resources - Mobile Resources (task executors) - Flowitems - ports - triggers - task sequences
• Libraries • Model Views
2
Models, Objects and Flowitems • Model - A collection of Flexsim objects representing withconcerned just enough detail to answer an system theactual questions you-are with!
• Object - A building block with inherited behavior, and user-definable attributes , variables , and visual properties . • Flowitem – the entities that flow through a model such as products, customers, paperwork, phone calls, etc. 3
Model Objects
Flowitems 4
Flexsim Model • A Flexsim model is a system of queues , processes , and transportation . – Queues develop naturally in a model when upstream arrival rates exceed the downstream processing rates. – Processing is simply a forced time delay on the object being processed. – Transportation is resource the physical movement of an entity from one to another.
5
Object Classification • FixedResources – objects which send and/or receive flowitems ex.
• TaskExecuters – mobile resources that perform assigned tasks ex. 6
Object Classification • Flowitems - The entities that are passed from one fixed resource to another within a model. • Flowitems are actually Flexsim Objects. • Flowitems hold information that can be set and queried in the model. – This information can do anything from defining process times to making routing decisions, and anything in between. 7
Model Behavior Most modeling behaviour is defined on the fi xed re so ur ces in a model:
– how long to process the flowitem – where to send the flowitem next – call a shared resource (operator) for processing the flowitem – call a mobile resource to transport the flowitem to the next fixed resource 8
Object Port Connections • Out pu t/Inp ut Por ts - Output-to-Input port connections define possible flowitem routes to/from Fix ed Reso ur ces . Input
Output
9
Object Port Connections • Cente r Ports - for referencing purposes, typically used to point to a TaskExecuter to be called for the processing or transportation of a flowitem .
Center 10
Concept of Triggers • When key events occur on an object , a trigger is fired. • The user may specify a variety of things to happen when a trigger fires (trigger logic). • There are triggers when a flowitem enters or exits an object. There are triggers when a process time finishes or a repair time is complete. • Each type of object has a unique set of triggers. 11
Triggers • An opportunity to define and customize system behaviour at a specific event occurrence. – Write/read information to/from a flowitem. – Change visual properties of flowitems or objects. – Send Messages to other objects. – Change objects. behavior of other – And much more…
12
Tasks and Tasksequences • task – a single instruction or action to be performed by a TaskExecuter object. ex. LOAD flowitem • tasksequence – a series of tasks to be performed in sequence. ex. TRAVEL to queue LOAD flowitem TRAVEL to processor UNLOAD flowitem 13
Library • Library - a list of class objects to be used in building a model. • Instance – a copy of one of the library objects - created in the model when an object is dragged from the library icon grid into a model view window.
14
Model Views A view is a window into the model. You can have several views open at the same time. Each view is a different perspective on the same mod el .
> Ort ho gr aph ic
Perspective > • Additional Views: – Planar – Tree
15
Basic Steps of Modeling in Flexsim 1 - Create a layout using library objects 2 - Make port connections 3 - Edit the look and behavior of objects 4 - Compile and run the simulation 5 - View the results
16
Mouse Operations • View Window Navigation: – Translate: left click-drag – Tilt and Rotate: right click-drag – Zoom: left&right click-drag (or scroll wheel)
• Object: – Translate in X and Y: left click-drag on object – Translate in Z: right&left click-drag on object
•• Highlighted = yellow box: left click Selected = red box: shift-click or ctrl-click – select multiple objects by shift or ctrl click-dragging a bounding box around a group of objects 17
Model 1 • Purpose – Introduction to the 5 basic steps of model building using a single queue, single server system (post office).
• Description
– people arrive at a post office every 60 seconds, on average. The statistical probability distribution which best simulates the inter-arrival pattern is an exponential distribution with a location value of 0 and a scale value of 60. – the service time at one and only service window in the post office is the lognormal(31, 3.1, 0.5) seconds. – if the queue for the service window exceeds 20 people, new arrivals are routed out of the model as “unhappy customers”. 18
Model 1 Layout
19
Step 1. Create a layout • Drag objects from the Library (icon grid) and drop them into the Orthographic Model View window using your mouse. • Reposition, resize, or rotate objects as desired using mouse.
20
Flowitem Flow • Flowitems are passed from one object to the next in zero time regardless of where in the model layout the objects are located. • To create time delay in the flowitem flow, add conveyors or task executers for transport . – Convey time depends on the conveyor’s length and speed. – Transport time between objects depends on the distance between the objects, plus the task executer’s speed, acceleration, & deceleration. 21
To scale or not to scale? Flexsim is a “unitless” platform. Time & length units are “user-definable” – consistency is the key! 1. Choose the time and distance unit that will be most common in your model. • •
time: milliseconds, seconds, minutes, hours, days, weeks, months, years, etc. distance: inches, feet, meters, kilometers, miles, etc.
2. Once you have chosen your time and distance units, make the mental connection that EVERY mea sur ement in you r model must be set in your chosen units. •
3.
Example: if you’ve chosen inches and hours, all speeds must be set in inches/hour. All positions are in inches from the model’s srcin. All time definitions (process & setup times, delayed messages, etc.) are in hours. Set all distances, positions, speeds, intervals - every u nit measur e in y our mod el, using the units that you’ve
chosen.
22
Port Connections • Objects can have an unlimited number of ports. • A port connection is needed for each possible routing choice in the model. • The actual port that a flowitem passes through depends on the selected rule for the object that is either doing the pushing or the pulling. (see Flow tab, Send To Port field). 23
Step 2. Make port connections • While pressing the “ A ” key, click-and-drag port connections between the objects. • Direction is important! Drag from the sending object to the receiving object.
• These output to input port connections are needed between the objects in your model that send and receive flowitems .
24
Viewing port connections • Display of port connections can be toggled on/off within the “View Settings” view sidebar. • The size of the port connectors can adjusted with thebe+/buttons. 25
Keys used for Port Connections
Disconnect
Outputs to Inputs
Center to Center
Q
W
A V
S C
Connect
View
26
Step 3. Edit the objects • Properties Window – Right click then choose Properties – Used to edit and view general info on all objects • • • • •
Visual shape, size, orientation, location Name a local toggles Port connections Labels Statistics
Window • Parameters – Double click (or right click then choose Parameters) – Used to edit object specific behaviour 27
Properties Window • Every ob ject has th e same se t o f p ro pert ies tabs
• Visual Tab – Look and size
• General Tab – Port connections – Display switches
• Labels (taught later) – User defined attributes • Statistics – Throughput, states, queuing, and stay times – Graphs, charts, readings 28
Object Size and Rotation • Objects can be repositioned, resized, and reoriented from the Properties window. • Additionally, objects can be manipulated from within the model view. – Reposition an object by leftclick dragging the object to a new location. – Be sure “Edit | Resize and Rotate Object” is checked • Left-click drag on the arrows to resize. – Up and right are larger – Down and left are smaller
• Right-click drag on the arrows to rotate.
29
Parameters Window • Each object class has its own Parameters Window • Parameters affect time that flowitems staythe in an object and how they are routed from object to object. • Apply will accept changes • OK will accept changes and close the window • Cancel will close the window without accepting changes • Properties button opens the Properties Window 30
Parameter tabs • Parameters are grouped into tab pages by category • Every fixed resource object will have a “ Flow ” tab and a “Triggers ” tab
31
Understanding the Basic Pick List
• The pick list • The code template (friendly editing) • The code edit (access to Flexscript/C++)
32
Understanding the Trigger Pick List
• The current code/selection • Add a pick-option to the code • Clear all of the existing code • The code template (friendly editing) • The code edit (access to Flexscript/C++) 33
Code Template Code • Template Blue text inmay the be replaced with any valid number, string or expression.
• These templates can be customized through the Cod e Edi t window. (to be taught later)
34
Ex. Change Source Arrival • The statistical probability distribution which best simulates the inter-arrival pattern is an exponential distribution with a location value of 0 and a scale value of 60.
35
Step 4. Compile and Run the Simulation • Compile the model (for models with C++ only) • Reset, Run • Control run speed with the slide control (has no effect on the simulation results) • The Execute menu can be used to set the Run Speed and Stop Time
36
Step 5. View the results • Create a Full, Summary or State Report using the “Statistics” menu •
Other reporting features to be discussed later: – VisualTool Object • Dynamic text – Recorder Object • Time plots, histograms, pie charts, historical and statistical tabular data – Object Properties Statistics Tab – Triggers writing to GlobalTables 37
Summary Report • Display a tabular report for all objects in model (or just those that are redselected). • Choose from a list of standard system variables to include in report. • Add user-selected attributes to the report. 38
Summary Report View
39
Flexsim State Report • State profile is listed for all objects in the model just those that are(or redselected ). • Displays amount of time or percentage of total simulation time an object was in each of its states. • CSV format (default viewer is Excel). 40
State Report View
41
Full Report • Requires Full History to be enabled – Statistics | Full History On
• Records data as the model runs • Data is saved in a database • Flexsim Chart makes charts from the saved data
42
Full Report View
43
Model 1 Follow Up • Questions – What’s the maximum and average time people wait in line? – How many unhappy customers? – What’s the utilization of the service window? – How many customers were serviced?
44
Model 2 • Purpose – learn how to duplicate objects – see affects of adding a second service window – introduction to the “Send to port” field (Flow tab)
• Description – add another service window to the post office
• Questions – answer the questions asked in Model 1 - Preview – if the windows differ by the type of service they can provide and 40% of the people need to use window 1 and 60% need to use window 2, how does the queue time increase? 45
Editing Selected Objects • Group editing can be performed on selected objects using the “Edi t Select ed Obj ect s ” menu in the view’s sidebar. • Only can be highlighted (YELLOW box) in a givenone viewobject window. • Multiple objects can be selected (RED box)
46
The Flexsim Object Library • The Flexsim Family Tree – Fixed Resource – Task Executer – Dispatcher
• Model 3 – Sink – Queue
- Multiprocessor - Seperator
- Transporter - Task Executer Teams
– Conveyor – Flow Node – Processor
- Combiner - Rack - Operator
- Network Node - Recorder - Visual Tool
47
Flexsim Family Tree Flexsim Object
Fixed Resource
Source
Dispatcher
Navigator
Task Executer
Network Node Network Node
Network Navigator
Visual Tool Visual Tool
Recorder
Operator
Queue Transporter
Sink
Traffic Control
Crane ASRS Vehic le
Rack
Robot
Reservoir Elevator
MultiProcessor
Conveyor
Processor MergeSort
Combiner Separator
48
Flexsim Standard Objects • Flexsim currently has 25 objects in its discrete object library. • Your ability to model will be determined by how well you understand these 25 objects and more importantly, the three main superclasses: – Fixed Resource – Task Executer – Dispatcher
• Extensive coverage of the Flexsim Object Library is found in the Flexsim Users Ma nu al. 49
FixedResource Superclass • FixedResource objects are the backbone of a simulation model. They’re used to define the product flow. • FixedResources can: – – – – –
push or pull flowitems process flowitems (forced delay) queue up flowitems (accumulate up to a max content) call for an operator to be utilized (for process / setup) call for a transport to carry flowitems to next resource
• There is no tr ansfer time between FixedResource objects unless a TaskExecuter is called to transport the flowitems. 50
TaskExecuter Superclass • TaskExecuters execute tasksequences. • A tasksequence is a list of tasks which are to be completed in the order listed. • A task is an activity such as loading, unloading, traveling, delaying, or simply being utilized. • When a TaskExecuter receives a tasksequence, it will start executing the tasks one after another until the tasksequence is either finished or preempted by a preempting tasksequence of higher priority . • Tasksequences are“Use created and dispatched “Use Transport” or Operator” boxes areautomatically checked on awhen th FixedResource. • Cust om taskseque nces can also be created and dispatched using commands (taught later). 51
Dispatcher Superclass • The Dispatcher receives tasksequences and either queues them up, or dispatches the tasksequences immediately to other Dispatchers and/or TaskExecuters connected to its output ports. • A tasksequence may preempt the current tasksequence part way through the current list of tasks. The preemption can either temporarily interrupt the current tasksequence or permanently destroy the current tasksequence as well as any other tasksequences waiting in the preempted TaskExecuter’s tasksequence queue. • Tasksequences can be sorted by their priority . • Because a TaskExecuter is a subclass of the Dispatcher, it too can act as a Dispatcher and be connected through its output ports to other TaskExecuters. 52
Model 3 •
Purpose Build a model which uses several objects in the Flexsim library
•
Description:
A part enters a Separator every 20s where it is split into 3 separate parts. Each part moves down one of three separate lines: 1. The first part moves via an “s”-shaped conveyor to a Combiner where a total of 8 parts are packed on a pallet (supplied by another Source). The loaded pallet is then conveyed to a Sink. 2. The second part is conveyed to a Queue where it is then carried by an Operator to a MultiProcessor object where 3 separate processing steps are performed. The first step can complete on it’s own in 3 seconds. The second step requires an operator (same operator that delivered the part) and takes 4 seconds, and the third step can complete on its own in 5 seconds. A Transporter then picks up the part and takes it to a Rack where it is stored. 3. The third part travels via FlowNodes to a Queue where 10 are accumulated before being released, one at a time, to a Processor with a 20 second cycle time. They are then placed in a Queue where a Robot transfers one part at a time over to a Sink. 53
Build Model 3 in Four Phases • Phase 1: Create Flow – Create flow with FixedResource Class objects only (neglect TaskExecuters).
• Phase 2: Add TaskExecutors – Add TaskExecutors: Operator, Transporter and Robot.
• Phase 3: Network Node Paths – Add a NetworkNode path to control the travel path of the Transporters.
• Phase 4: Reporting – Add a 3D pie chart to show the status of the Operator – Add 3D text to show the content of the Rack
54
Phase 1 Description
• Phase 1: – Obtain flow with FixedResource Class objects only (neglect TaskExecuters). 55
Source • The Source is used to introduce flowitems into the model. • The arrival rate of flowitems will be based on an Inter-Arrival Time, Arrival Schedule or Sequence. • Most models will start with a Source.
56
Sink • The sink is used as an exit point for flowitems. • FlowItems can only ‘exit’ the model via the Sink • Your last chance to record information about th flowitems is in the OnEntry trigger of the Sink.
57
Queue • The Queue is used to stage FlowItems for downstream operations. • Queues are used in the model wherever work-inprocess (WIP) exists between process steps. • A Queueline, mayorbe a table, basket, waiting room. 58
Conveyor • Used to convey flowitems from one location in the model to another location. • Time to convey depends on the conveyor’s length divided by its speed. • Can be accumulating or not. If not, all parts on the conveyor stop when a part at reaches the end of the conveyor and is blocked (like a Belt conveyor). • Conveyors can take the actual length of the flowitems and the Conveyor sections into account when calculating accumulation and available space. • You can define a combination of many straight and curved sections all on one conveyor object! 59
Flow Node • The FlowNode is used in a model where it is
• • • •
desirable to path havetoflowitems move along designated another object in the a model consuming time as they move. One use would be to move people (flowitems) down an open corridor or in a building. Similar to a Conveyor and is connected to other FlowNodes and FixedResources. Each FlowItem can have its own speed. Flowitems DO NOT spatially accumulate.
60
Processor • A Processor is used anytime an operation is performed on a FlowItem. • A Processor can be any kind of machine or station; anything that would take time to manipulate a FlowItem. • The FlowItems must stay in the Processor for the sum of the Setup Time and the Process Time plusinclude any Blocked Time. The dwell time may also time waiting for an operator, time waiting for a transporter and time waiting for the Processor to be repaired if broken down. 61
Order of Execution (pushed flowitem) flowitem enters
OnEntry
Pick Operator
Process Time
delay
OnProcessFinish
OnExit
delay
SetupTime
Pick Operator
OnSetupFinish
Request Transport From
delay
Send To Port possible delay
62
MultiProcessor • The MultiProcessor allows you to perform several operation steps at one location. • Each operation can have a different process time, and use a different number of operators. • A MultiProcessor is a good object to use when you have large flowitems that move to a spotperformed where several operations are before it moves again. • Only 1 flowitem at a time is allowed in the MultiProcessor. 63
Combiner • The Combiner is used to pack or join flowitems • When using the pack option, the flowitems which enter ports 2 and higher are placed inside of the flowitem which entered port 1. • When using the join option, the flowitems which enter ports 2 and higher are destroyed, and the flowitem which entered port 1 represents the “assembled” part. • Note: Component rows are added automatically for each input port connections made for ports 2 and higher. first input port i s • The alw ays r eserved for t he
•
con taine r or main pa rt! The ass um ed t arg et qua ntit y is on e !! 64
Separator • The Separator is used to separate (unpack) or to split (make copies of) flowitems. • It can unpack flowitems that were previously combined using the Combiner. • Flowitems can be split into a specific number or call from a table. • The contents must leave before the container can leave
65
Rack • specific The Rack is used to store flowitems in a column and row (bay and level). • You can toggle between three different visual displays of the Rack by holding the “X” key and clicking on the Rack. • The physical configuration is defined by the Rack layout size table. 66
Rack Tabs
67
Complete Phase 1
68
Phase 2 Description
• Phase 2: – Add TaskExecuters: Operator, Transporter and Robot. 69
Operator • An Operator will model human tasks such as machine setup or manual assembly. • The Operator can also be used to transport FlowItems from one FixedResource to another. • It really has no additional functionality beyond the TaskExecuter itself. • The Operator can move in x, y, and z directions.
70
Transporter • A Transporter is used in a model where a fork truck, AGV or some other transport vehicle might be used. • It is used to transport FlowItems from one FixedResource to anothe • The Transporter can travel in x, y and z directions. • During offset travel the forks lift or lower in the z direction as neede to pick or place flowitems. • Transporters can load many FlowItems from multiple locations and then unload the FlowItems separately to multiple locations.
71
Other Task Executers
72
Forming a TaskExecuter team
Center
Output
Dispatcher TaskExecuters
Input 73
Complete Phase 2
• Bonus: – Try replacing the robot with a Crane. Play with the crane’s parameters to get a feel for how it works.
74
Phase 3 Description
• Phase 3: – Add a NetworkNode path to control the travel path of the Transporter.
75
NetworkNodes • NetworkNodes are used to define the path a TaskExecutor will follow when executing its travel tasks • A network path is made up of a group of interconnected NetworkNodes. • A TaskExecuter is assigned to move on the network by connecting it to any NetworkNode in the path. The connected node becomes the TaskExecuter’s “home” node. • If a FixedResource is visited by a task executor assigned to travel on the network, that FR must be connected to at least one NetworkNode, making it accessible via the network.
76
Connecting NetworkNodes • Click-and-drag a connection while pressing the “A” key. • When connected you will see a black line between the nodes. Two green direction indicators show that travel is allowed in both directions. 77
Connecting a Fixed Resource to the Network • Click-and-drag a connection, while holding the “A” key, between a NetworkNode and the object where the load takes place. • A blue line will show the connection. The line does not connect to any port. 78
Connecting a TaskExecutor to the Network
• Click-and-drag a connection between the TaskExecutor and a NetworkNode while pressing the “A” key.
• A red line will indicate that the connection has been made. The line does not connect to any port. 79
Single Direction Paths • A path can be restricted to travel in single direction byapressing the “Q” key and clickdragging in the direction you want to disallow travel.
• indicator The greenturns direction red, showing the restricted direction. 80
Non-Passing Paths • A non-passing path can be toggled by using the “A” key and click-anddragging between two nodes that are already connected. • The direction indicator turns yellow, showing a
No t rave li ng
non-passing direction. • “A” dragging a red or yellow direction will toggle back to green.
Trave l bu t no p assi ng 81
Direction Indicator Context Menu Rather than “A” dragging the path to toggle path type, you can right click a direction indicator and choose from a context menu. “X” clicking a direction indicator with the mouse button will also toggle through the different direction modes. Use the “Travel Networks” section of the view sidebar to set connection defaults and increase the size of the network nodes.
82
Spline Control Points • To create a curved path select “Curved” from the direction indicator context menu. • Spline control points will appear on the path. • Drag the spline control points to create a curved path.
83
NetworkNode View Modes 1. a
• The display options for the network can be toggled by holding down the “X” key
2. A
and then clicking on any NetworkNode.
3. A
4. A
5. A
6. a
84
Paths Tab • Each path from a NetworkNode can be edited in many ways. • Different direction modes can be set using the “Connection Type” dropdown list. • Minimum spacing between travellers can be defined. • A maximum speed can be set for this path connection. • A Virt ual Distance can be set. Virtual distance is a forced distance value. Using virtual distance, you can give a path an artificial length. When migh t a virtu al di stance be use ful ?
85
Complete Phase 3
• Bonus: – Try adding a second Transporter to the Multiprocessor. – Can you make the Transporters travel in a counter-clockwise direction?
86
Phase 4 Description
• Phase 4: – Add a 3D pie chart to show the status of the Operator – Add 3D text to show the content of the Rack 87
Recorder • The Recorder is used to display and record statistical information. • The Recorder can display 3D charts and graphs from object data or tables. • Enable the object to record data for Content and Staytime graphs (Statistics tab of Properties window). • Can gather point statistics (min, max, avg) or complete historical data at set time intervals or based on actual object events. 88
VisualTool • The VisualTool is one of the most versatile Flexsim Objects. • VisualTool can be used as a prop to display planes, cubes, columns, spheres, imported objects (2D CAD or 3D shapes), 3D text and even presentation slides (bmp, jpg). • The VisualTool can also act as a container for other objects.
89
Complete Phase 4
• Bonus: – Can you change the 3D shape of the Operator? 90
Flexs im Hiera rchy
And
The Mod eli ng Lang uage
91
What is a Node? • Basic data structure of Flexsim is a hierarchal tree – main tree (model and project related objects and data) – view tree (GUI related objects and picklists) – model tree (model related objects and data)
• The node is the basic building block of a tree • Nodes hold all the information behind the scenes for objects, GUIs and data.
92
Node Structure • Nodes have a name • Nodes can have a data item – number – string – object
• If nodes have object data, use > to view a separate node list containing the object info (data members and member functions) • If nodes contain sub nodes, use + to expand and view the child nodes 93
Node Symbols Standard Folder Object Object data Function (C++) Function (FlexScript)
94
Sample Model Tree
95
What is a function? functionname( argument1, argument2, etc)
• An argument can be:
– Numerical value – String (“text“) – Pointer (*) to an object or node
• Function example:
colorrandom(item)
– (see OnExit trigger of a Source object)
• Many of Flexsim’s functions are used to read data from the tree and save data to the tree.
96
General Rules • language is case sensitive (A does not equal a) • no specific format is required (free use of spaces, tabs and line returns is encouraged for “readable” code) • text strings are entered between quotes. “mytext” • parenthesis follow a function call and commas separate the arguments of the function. moveobject(object1, object2); • a function or command will always end with a SEMI-COLON (;) • parenthesis can also be used freely to make associations in your math and logic statements. Ex: ((x+3)*2) • curly braces { } are used to define a block of statements. • to comment the rest of a line use // and ty pe not e here • multi-line comments start with /* and end with */. • don’t use spaces or special characters in name definitions ( _ is ok). • names may include numbers, but may not begin with a numbe (machine_9 is acceptable, 9machine is not). 97
Logic Statements - Available Help – Existing Pick List options are great examples – Commands – Hints
98
Variable Types • • • •
int double string treenode
integer (1, 2, 3, 14324) double precision (2.5, 3.14159) text string (“Anthony was here.”) reference to a node in the tree
99
Declaring and Setting Variables • int index = 1; • double weight = 175.8; • string category = “groceries”; • treenode forklift = centerobject(current,1);
100
Math Operators • • • • • • • •
x+y x- y x*y x/y sqrt(x) pow(x,y) round(x) frac(x)
•• fmod(x,y) min(x,y) • max(x,y)
x plus y x minus y x times y x divided by y square root of x x to the power of y (xy) x rounded to the nearest integer returns the decimal portion of x returns the remainder of x/y returns minimum of x and y returns maximum of x and y 101
Comparing • • • • • •
x>y x= y x Output Console
• example – pt(“Item In “); pt(getname(current)); pt(“ “); pf(time()); pr(); 110
Processor Parameters • Understanding the edit fields of the Processor object will help you understand Flexsim. • You should be able to answer the following four questions about each edit field: – what is its purpose? – when is it evaluated? – what are its access variables? – what does it return?
111
Access Variables & Returns EditField
AccessVariables
SetupTime
current,item,port
Process Time
current, item
MTBF MTTR Send To Port Pull From Port
Returns
delaytime delay time
current
delay time
current current, item
delay time port number
current
port number
PullRequirement
current,item,port
true/false(1/0)
RequestTransportFrom
current,item,port
numericpointer
PickOperator
current,item
numericpointer
OnReset
current
N/A
OnMessage
current, msgsendingobject, msgparam1, msgparam2, msgparam3
N/A
OnEntry
current, item, port
N/A
OnExit
current, item, port
N/A
OnSetupFinish
current, item
N/A
OnProcessFinish
current, item
N/A
OnBreakDown
current
N/A
OnRepair
current
N/A
Code Exercise 1 • Purpose – Gain experience in writing code in the Code Edit windows. – windows. Introduction to special comments used to define Code Template – Introduction to the bernoulli command. bernoulli(num probability, num succeed-value, num fail-value, [num stream])
• Description – Do not use code templates for these exercises (write your own code, beginning with most basic available option)! – See next slide for model layout description. – Using the “Send To Port” field of the Conveyor, send 30% of the flowitems to port 1 and 70% to port 2 (Use the bernoulli command).
113
Code Exercises 1,2,3 Layout
114
Logical ‘if’ Statement if (test expression)
if (content(item) == 2)
{
{ code block
} else { code block
}
colorred(item); } else { colorblack(item); }
115
Code Exercise 2 • Purpose – Learn how to both set and read the itemtype of a flowitem using code. – Introduction to the Flowitem Bin
• Description – – – –
Uses same layout as Exercise 1. Set the itemtype of flowitems as they exit the Source. 60% of the flowitems are itemtype 7, the rest are itemtype 3. Using an “if” statement in the “Send To Port” field of the Conveyor, send flowitems with itemtype 7 to port 1, and those with itemtype 3 to port 2.
• Questions – Can you change the color of the Flowitems based on their itemtype using code? How can you find the color commands? 116
The Flowitem Bin • Sources create copies of objects in the Flowitem Bin • Any changes made to objects in the Bin affect the flowitems that are created by Sources • Used to create labels, set size, color, shape, etc. 117
Labels • labels – information can be stored on flowitems (and other modeling objects) in the form of labels. • Flowitems and other Flexsim objects can have an unlimited number of labels. • Labels have a name and data . The data may be numeric, string, list, or table. 118
• syntax
Object Labels
– getlabelnum( object, “labelname” ) – setlabelnum( object, “labelname” , value ) – getlabelstr( object, “labelname” ) – setlabelstr( object, “labelname” , string ) – label( object, “labelname” )
• examples – – – – –
getlabelnum( item, “serialnumber” ) setlabelnum( item, “serialnumber”, 5 ) getlabelstr( current, “category” ) setlabelstr( current, “category”, “groceries” ) inc( label(item, “stepnum”), 1 ) • The increment command only works with number data nodes 119
Logical ‘switch’ Statement int type = getitemtype(item); switch ( switchvariable ) { case casenum: { code block break; } case casenum2: { code block break; }default: { code block break; } }
switch (type) { case 1: { coloryellow(item); break; } case 5: { colorred(item); break; }default: { colorgreen(item); break; } }
120
Code Exercise 3 • Purpose – Learn how to both set and read the labels on a flowitem using code.
• Description – Uses same layout as Exercise 1. – Create a numeric label named “routing” on the Textured Colored Box in the FlowItem Bin (see toolbar). – Set the “routing” label of flowitems as they exit the Source with a random number between 1 and 4 (use duniform() command). – Use a switch() statement in the “Send To Port” field of the Conveyor to send flowitems according to the following rules: •• Label Label values values 1 2 and and 3 4 go go to to port port 2 1
• Questions – Can you change the color of the flowitems based on their label value using code? 121
Logical ‘while’ Statement wh il e ( test expression) { code block
}
while (content(current) > 0) { destroyobject(last(current)); }
In programming, a whil e loop is a control structure that allows a code block to be repeated as long as a test expression is true. Avoid infinite loops by ensuring that the test expression will eventually fail. 122
Logical ‘for’ Statement for ( start expression; test expression; count expression) {
//code block }
for (int index=1; index