Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Entren Amien To Basic of Lex Sim
Entren Amien To Basic of Lex Sim
Ocampo, MSc
Flexsim Centroamérica
• Capitulo 1. Introducción a la Simulación
• Capitulo 2. Introducción a Flexsim
• Capitulo 3. Pasos de Modelado en Flexsim
• Capitulo 4. Librería de Objetos de Flexsim
• Capitulo 5. Funciones y Declaraciones
• Capitulo 6. Conceptos y Modelos
2
Introducción a la Simulación
La simulación es la imitación de un
sistema, basado en conocimiento o
supuestos acerca del comportamiento
de las partes de ese sistema, con el
propósito de obtener una idea del
comportamiento de todo el sistema.
4
Simulación es la imitación de un sistema
dinámico utilizando un modelo
computarizado para poder evaluar y mejorar
el desempeño de un sistema.
5
Un modelo es una abstracción (hecha
a propósito). Solo debería contener
aquellos elementos de la realidad que
son necesarios para resolver el
problema. El modelo mas sencillo es el
mejor modelo posible para cumplir con
el propósito.
6
Conceptos de Simulación
8
Simulación de Eventos-Discretos
• Ejemplos de EVENTOS de un sistema:
– arribo de ordenes/partes, descanso de un operario
– movimiento de un producto: recolección, entrega
– comienzo y final de un proceso de maquinado
– descompostura de una maquina, reparación
10
Concepto de Simulación
Los eventos secundarios son generados
internamente por un modelo lógico. Ejemplo: en
una línea de espera el servicio se inicia hasta
cuando un servidor esta libre y el evento es
programado a ocurrir inmediatamente.
11
Concepto de Simulación
12
En el caso de una línea de manufactura..
– De un ejemplo de entidad dinámica
– De un ejemplo de entidad no-dinámica
– De un ejemplo de evento primario
– De un ejemplo de evento secundario
– De un ejemplo de recurso
13
Ejemplo de Simulación (Promodel)
14
Ejemplo de Simulación (Flexsim)
15
1950 2000
• Desafíos de los nuevos sistemas
1. Ciclos de vida mas corto – Debido a cambios de
producto mas frecuentes y radicales y a
actualizaciones del sistema mas frecuentes.
Cost
System Stage
18
• Debido a estos desafíos y a los problemas que las
actuales herramientas de planeación tienen es
necesario el uso de mejores herramientas que:
1. Sean flexibles
2. Sen confiables
3. Sean rápidas y fáciles de utilizar
O se a
19
• La simulación es:
– Rápida y fácil de usar
21
• ¿Cuales son los desafíos de la manufactura
moderna?
• ¿Que ventajas tiene la simulación sobre otras
alternativas en el diseño de un sistema?
• ¿Cómo la actividad de modelar por si misma
(sin correr el modelo) ayuda en el diseño de
un nuevo sistema?
• ¿Puede la simulación por si misma mejorar el
diseño de un sistema?
22
Entradas y Salidas de la Simulación
Bus. Processes Supply Chain
23
Preguntas de Revisión
a. ¿Que razones existen para que aumente la
popularidad de la simulación por
computadora?
b. ¿Como sigue la simulación el método
científico?
c. ¿Que tan importante son las estadísticas para
hacer simulación?
d. ¿Es un ejercicio de simulación desperdiciado
si no se encuentran problemas? Explique
24
25
• Un software de simulación es formado por objetos
que pueden ser utilizados dentro de un modelo
para representar diferentes actividades en un
sistema.
- Abraham Maslow
31
Otras alternativas (herramientas)
• Mientras la simulación es tal vez la herramienta
de análisis de sistema más versátil y poderosa,
otras técnicas están disponibles que pueden ser
de ayuda en la planeación de sistemas.
32
¿Cuando No Utilizar Simulación?
• Ejemplos:
– Modelos Estadísticos
– Modelos de Teoría de Colas
– Modelo de Sistemas de Inventarios
35
• Parte de la Investigación Operativa que
estudia el comportamiento de sistemas
cuyos elementos incluyen líneas de
espera (colas).
36
Entidades que arriban Queue Servidor Entidades que salen
38
• Los elementos mas importantes en un sistema de colas:
clientes y servicio.
• Los clientes se caracterizan por los intervalos de tiempo que
separan sus llegadas.
• El servicio se caracteriza por el tipo y tiempo de servicio,
además de por el numero de servidores. El tipo de servicio o
disciplina representa el orden en el que los clientes se
seleccionan de la cola.
• Las llegadas de clientes pueden ser deterministas o
aleatorios (en este caso se modelan mediante una
distribución estadística).
41
• Pueden ser impacientes.
42
• Puede ser de uno o varios canales.
43
• Pueden existir uno o varios servidores.
• Se suele asumir independencia entre tiempos de
servicio.
• Duración de los servicios: deterministas o aleatorios.
• Tasa de servicio: m = numero medio de clientes que
son atendidos por unidad de tiempo.
• Tiempo medio entre llegadas: 1/m.
44
Una vez caracterizado el sistema, se puede contestar:
• ¿Que proporción de tiempo están los servidores
desocupados?
• ¿Cual es el tiempo medio de espera para un cliente?,
¿es este un tiempo razonable?, ¿se pierden clientes
por tiempos de espera largos?
• ¿Es conveniente añadir mas servidores para reducir
el tiempo medio de espera?
• ¿Cual es el numero medio de clientes en cola?
• ¿Cual es la probabilidad de que la espera sea mayor
que una determinada longitud en un tiempo
determinado?. 45
• Notación de Kendall: las características del
sistema se especifican por los símbolos:
A/B/s/k/t/d
donde A y B denotan las distribuciones de los
tiempos entre llegadas y de servicio,
respectivamente.
s denota el numero de servidores en paralelo
o canales, k denota la capacidad del sistema,
t denota el tamaño de la fuente de entrada, y
d es la disciplina de la cola.
46
• La distribución puede ser
– M Exponencial
– D Constante o determinista
– Ek Erlang de parámetro k
– G Genérica e independiente
48
• Dados los siguientes parámetros (estimados
usualmente de manera estadística):
= tasa de llegadas
= tasa de servicio
- s = numero de servidores
• Se calcula:
51
52
Avg Depth
10 ft.
53
• Los elementos de un sistema
operan en forma conjunta unos
con otros, esto significa que
muchas veces se forman
interacciones muy complejas
• Desafortunadamente, la intuición
humana no es muy buena
analizando y entendiendo
sistemas complejos
54
1. Interdependencia entre elementos de
forma que cada elemento afecte a otros
elementos
2. Variabilidad en el comportamiento de los
elementos que produce incertidumbre
55
• Las Interdependencias causan que el comportamiento de
un elemento afecte otros elementos en un sistema.
58
Grado de
dificultad
analítica
Numero de interdependencias y
variables aleatorias
59
• Interdependencias
– Interacciones de flujo
– Restricciones por recursos
compartidos
• Variabilidad
– Tiempos de Actividades
– Decisiones, Cantidades
– Eventos, Atributos
60
• mejorar utilización del equipo
• reducir tiempo en espera y tamaños de los queue
• alocar recursos eficientemente
• eliminación de problemas de stock-out (shortage)
• minimizar los efectos negativos de breakdowns (descomposturas)
• minimizar los efectos negativos de rechazos y desperdicio
• estudiar ideas de inversión alternativas
• determinar tiempos de throughput de las piezas
• estudiar planes de reducción de costos
• establecer tamaños óptimos de lotes y secuencia de piezas
• resolver problemas de manejo de materiales
• estudiar el efecto de tiempos de preparación (setup times) e intercambio
de herramientas (tool changeovers)
• optimizar lógica de prioritización y despacho para productos y servicios
• entrenar operadores en el comportamiento general del sistema y
desempeño relacionado con el trabajo
• manejar toma de decisiones operacionales en el día-a-día
61
Elementos de un Sistema de
Procesamiento
• Desde la perspectiva de simulación, se
puede decir que un sistema consiste de
entidades, actividades, recursos y
controles.
62
los productos (items)
procesados a través del sistema.
• Humanos o animados
• Inanimados
• Intangibles
• Continuos
63
las tareas desarrolladas
directamente o indirectamente en soporte del
procesamiento de entidades.
64
los medios mediante los
cuales las actividades son desarrolladas.
• Humanos
• Inanimados (maquinas, espacio de piso)
• Intangibles (energia, datos)
65
determina como, cuando y
donde se desarrollan las actividades.
• Planes
• Políticas
• Schedules
• Instrucciones
• Lógica de control
66
Ambiente de Modelado y Simulación
Model Adequacy
Recolección
de Datos Sistema Modelo
bajo del
Análisis
Estudio Sistema
“Programación”
Validación Verificación
Modelo de
Simulación
Interfase Flexsim
Cambiar parámetros o estructura,
correr, obtener resultados 67
Density Function Plot Density Function Plot
0.80
1.00
0.70
0.60
0.75
0.50
f(x)
f(x)
0.40 0.50
0.30
0.20 0.25
0.10
0.00 0.00
-0.50 0.00 0.50 1.00 1.50 2.00 0.0 1.0 2.0 3.0 4.0 5.0 6.0
X-Value X-Value
3 - Normal 2 - Exponential
0.70 0.60
0.50 0.40
0.40
0.30
0.30
0.20
0.20
0.10
0.10
0.00 0.00
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 2.25 2.50
X-Value X-Value
1 - Weibull
4 - Lognormal
68
Also: Bernoulli
• Una de las características más grande de la
simulación es su habilidad de imitar el
comportamiento aleatorio o la variación que es
característica de los sistemas estocásticos.
0 .1 .2 .3 .4 .5 .6 .7 .8 .9 1.0
Números Aleatorios
• Note que para esta función particular de probabilidad acumulativa
mientras el número aleatorio se acerca más a 1, la extensión entre
las variantes aleatorias correspondientes disminuye. Observe, el
hecho que la mitad de las variantes aleatorias generadas (de 0 al
0.5) toma ásperamente el 80% del rango total de los valores.
75
• Para determinar el resultado siguiente para un evento
aleatorio, un número aleatorio es generado (es decir un
valor uniformemente distribuido entre 0 y 1)
• El valor de la variable aleatoria entonces se compara con
el valor de la probabilidad definida para el evento. Si el
valor es menor que o igual a la probabilidad definida para
el resultado, se observa el resultado, si no el resultado
alternativo ocurre.
incoming parts .80
• Para ilustrar esto, suponga Inspection
pass
que las partes pasan por
una operación de
inspección el 80% del .20
tiempo y fallan la inspección
el 20% del tiempo fail
76
• ¿Que tipos de simulación serán cubiertas en este
curso?
• ¿Cuales son algunos ejemplos de variables aleatorias
en un sistema?
• ¿Que es un generador de números aleatorios y que
rango de valores genera?
• ¿Que es una variante aleatoria y como se generan?
77
• La variables aleatorias de un sistema deben de
modelarse de acuerdo a ciertas ecuaciones
matemáticas que sean capaces de reproducir su
variabilidad
• En la mayoría de casos, dicha variabilidad puede
clasificarse dentro de alguna distribución de
probabilidad, por lo que, uno de los pasos mas
importantes de todo proceso de modelado estocástico
es el encontrar el tipo de distribución de probabilidad
que modele la variabilidad de los datos de entrada del
sistema.
78
Rate of
Arrival
10:00 a.m. 12:00 a.m. a.m. 2:00 p.m. 4:00 p.m. 6:00 p.m.
Time of Day
Repair Time
Probability
.6
probabilidad pueden ser:
.4
.2
– discretas (describen la
0
probabilidad de que ocurran 0 1 2 3 4 5 6 7
valores específicos) Value
1.0
.8
– continuas (describen la
.6
probabilidad de que un valor
fx .4
este dentro de un rango
dado). .2
0
0 1 2 3 4 5 6 7
Value
83
• Las distribuciones discretas mas usadas en la
modelación de sistemas son:
– Bernoulli
– Uniforme Discreta
– Binomial
– Poisson
– Geométrica
84
Función de 1 p si x 0
Densidad:
p( x) 1.0
p si x 1 f(x)
0 si x 0 0.5
Distribución
Acumulada: F ( x) 1 p si 0 x 1
0 1
1 si x 1 x
0 si x i
Distribución
Acumulada: F ( x) x i i si i x j a b
1 si j x x
0 si x 0
0 1 2 3 4 5 6
x n i1 p 1
F ( x) x p si 0 x n x
i 0 i
1 si x n
Función de Densidad:
x
e
si x 0, 1, f(x)
p( x) x! 0.1
0 de otra manera
Distribución Acumulada:
0 1 2 3 4 5 6 7 8 9 10
x i
x
F ( x) e si x 0
i 0 i!
1 (1 p) x 1
si x 0 0
F ( x) 1 2 3 4 5 6 7
0 de otra manera x
b a
Distribución Acumulada: x a
F ( x)
b a a b
1 x/
Función de Densidad: f ( x) e
x/
Distribución Acumulada: F ( x) 1 e
x
f(x)
1 (x / )
Función de Densidad: f ( x) x e =2
(x / )
Distribución Acumulada: F ( x) 1 e
x
=1.0, =2.0
=.5, =.5
f(x)
Función de Densidad: SE BUSCA!!
f(x)
2
– Prueba de bondad de ajuste
– Prueba de Kolmogorov-Smirnov
100
• Existe software especializado que le hace
estas pruebas de bondad de ajuste al set de
datos que están siendo analizados y que
presenta todas aquellas distribuciones que
no pueden ser rechazadas junto con el
ranking (probabilidad de que esta sea la
distribución que mejor se acerque a la
realidad) que estas presentan
• Dos ejemplos de este tipo de software son:
– ExpertFit (Usado por Flexsim, y Simul8)
– Stat::Fit (Usado por Promodel)
101
102
103
Terminología de Flexsim
Modelo 1 - Preview
• Propósito
– Correr y analizar su primer modelo de simulación en Flexsim!
105
Modelo 1 - Preview
• Instrucciones
1. Open > Modelo_1.fsm
2. Reset, Run
4. Control de Velocidad
5. El modelo parara después de 8 hrs.
• Preguntas
1. ¿Cual es el tiempo máximo y promedio que la
gente espera en fila?
2. ¿Cuantos clientes no-felices hubieron?
3. ¿Cuál es la utilización de la ventana de servicio?
4. ¿Cuantos clientes fueron servidos?
106
• Un modelo en Flexsim es básicamente un
sistema de queues, procesos, y transporte.
• El procesado es simplemente un tiempo de
retraso forzado en una entidad.
• El transporte es el movimiento físico de una
entidad desde un recurso hasta otro.
• Los queues se desarrollan de manera natural
en un modelo cuando las tasas de arribo
exceden las tasas de procesamiento.
107
• Tipos de objetos para el modelado en
Flexsim:
– Recursos fijos (i.e. queue, processors)
– Recursos compartidos (i.e. operators)
– Recursos móviles (i.e. forklifts, elevators).
109
• Objeto – un bloque de construcción con
comportamiento heredado, y atributos, variables y
propiedades visuales definidas por el usuario.
112
113
• Clase RecursosFijos – objetos que
reciven y/o envían flowitems
ej.
Output
Input
116
• Puertos Centrales – usados para propósitos
de referencia, típicamente para señalar a un
TaskExecuter para que sea llamado para el
procesamiento o transporte de un flowitem.
Center
117
• Cuando eventos claves ocurren en un objeto, un trigger
es disparado.
118
• Son una oportunidad para
definir y personalizar
comportamiento de un
sistema en la ocurrencia
de un evento especifico.
– Write/read information
to/from a flowitem.
– Change visual properties of
flowitems or objects.
– Send Messages to other
objects.
– Change behaviour of other
objects.
119
Pasos de Modelación en
Flexsim
Pasos Básicos para el Modelado en
Flexsim
1 - Cree un layout usando la librería de objetos
2 - Haga las conexiones con los puertos
3 - Edite el look y comportamiento de los
objetos
4 - Compile y corra la simulación
5 - Vea los resultados
121
Operaciones con el Ratón
• Navegación de Ventana:
– Trasladar: clic izquierdo y arrastrar
– Girar y Rotar: clic derecho y arrastrar
– Zoom: clic izquierdo y derecho (o scroll wheel)
• Objeto:
– Trasladar en X y Y: clic izquierdo en el objeto
– Trasladar en Z: clic izquierdo y derecho y arrastrar en el objeto
– Rotación en X,Y,Z: clic derecho y arrastrar en el objeto
– Tamaño en X y Y: clic izquierdo y arrastrar en el punto amarillo
– Resize Z: clic izquierdo y derecho y arrastrar en el punto amarillo
(o usar el scroll wheel cuando el objeto esta seleccionado)
• Resaltado = caja amarilla: clic izquierdo
• Seleccionado = caja roja: shift-clic o ctrl-clic (+arrastrar)
122
Modelo 1
• Propósito
– Introducción a los 5 pasos básicos de la construcción de un
modelo usando un sistema de un solo queue y servidor (oficina
postal)
• Descripción
– La gente llega a la oficina postal cada 60 segundos en
promedio. La distribución de probabilidad estadística que mejor
simula el patrón de inter-arribo es una distribución exponencial
con un location value de 0 y un scale value de 60.
124
Paso 1. Cree un layout
• Arrastre objetos de la librería y colóquelos en la ventana ortográfica
usando el ratón.
• Reposicione, cambie de tamaño, o rote los objetos usando el ratón.
125
Flujo de los Flowitems
• Flowitems pasan de un objeto al siguiente en
tiempo cero no importando en donde en el
modelo estos estén localizados.
• Para crear un tiempo de retraso en el flujo del
flowitem, agregue bandas transportadoras o
task executers para su transporte.
• El tiempo de movimiento depende de la longitud
y velocidad de la banda transportadora.
• El tiempo de transporte entre objetos depende
en la distancia entre los objetos y la velocidad,
aceleración y desaceleración del task executer.
126
• Las unidades de Tiempo & Longitud son
“definibles por el usuario” – la clave es la
consistencia!
127
Conexiones de Puerto
• Los objetos pueden tener un numero ilimitado
de puertos.
128
Paso 2. Haga conexiones de puerto
• Mientras aprieta la tecla “A”, haga clic y arrastre conexiones de
puerto entre los objetos.
• Estos puertos de conexión de salida a entrada son necesarios
entre los objetos en su modelo que envían y reciben flowitems.
129
Viendo las conexiones de puerto
• Las conexiones de
puerto pueden
mostrarse u ocultarse
desde la opción de
“Settings”.
• El tamaño de los
puertos puede también
ser ajustado (trate
Connector Size = 0.3)
130
Teclas usadas en la Conexión de Puertos
Outputs to Inputs Center to Center
Desconectar
Conectar
Ver
131
Paso 3. Edite los objetos
• Ventana de Propiedades
• Visual Tab
– Look y tamano
• General Tab
– Conexiones de puerto
– Display switches
• Labels (ensenado luego)
– Atributos definidos por el usuario
• Statistics
– Throughput, states, queuing, and
stay times
– Graphs, charts, readings
133
Ventana de Parámetros
• Cada objeto clase tiene su
propia Ventana de
Parámetros
• Los parámetros afectan el
tiempo que los flowitems
están en un objeto como
estos son enrutados de
objeto a objeto.
135
Entendiendo la Lista de Selección
(Combo Box)
136
Preforma de Código
• El texto en azul en la
preforma de código puede
ser reemplazada con
cualquier Flexscript valido.
138
• Reset, Run
• Controle la velocidad de
corrida con el slide control
(no tiene efectos en los
resultados de la simulación)
141
Standard Report View
142
Flexsim State Report
• Un profile de los
Estados es
mostrado para cada
objeto seleccionado
(rojo) en el modelo.
143
Seguimiento al Modelo 1
• Preguntas
– ¿Cual es el tiempo máximo y promedio que la
gente espera en fila?
– ¿Cuantos clientes insatisfechos hubieron?
– ¿Cual es la utilización de la ventana de servicio?
– ¿Cuantos clientes fueron servidos?
• Extra
– Agregue Modelo_1.dxf al modelo. Modifique su
layout de acuerdo a este documento.
(nota: rótelo 90 grados alrededor de x)
144
144
Modelo 2
• Propósito
– Aprenda como duplicar objetos
– Vea el efecto de agregar una segunda ventana de
servicio
– introducción al campo “Send to port” (Flow tab)
• Descripción
– Agregue otra ventana de servicio a la oficna de
correos
• Preguntas
– Responda a las preguntas hechas en el Modelo 1
– Si las ventanas difieren por el tipo de servicio que
pueden proveer, y 40% de la gente necesita usar la
ventana 1 y 60% necesita usar la ventana 2,
¿como el tiempo en el queue aumenta?
145
• Edición de grupos puede ser desarrollada en objetos
seleccionados usando el menú “Edit Selected Objects”.
• Solo un objeto puede ser resaltado (caja AMARILLA) en
una ventana dada.
• Múltiples objetos puede ser seleccionados (caja ROJA)
146
La Librería de Objetos de
Flexsim
148
Flexsim Standard Objects
• Flexsim has 25 objects in
the entire library.
• Your ability to model will
be determined by how well
you understand these
basic 25 objects and their
3 superclasses.
• Extensive coverage of the
Flexsim Object Library is
found in the Users Manual
under Help.
149
• FixedResource objects are the backbone of a
simulation model. They define the flow of the
model.
• FixedResources can:
– push or pull flowitems
– process flowitems (forced delay)
– queue up flowitems (accumulate up to maxcontent)
– call for an operator to be utilized (for process / setup)
– call for a transport to carry flowitems to next resource
150
• 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.
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 process can complete on its own in 5 seconds. A
Transporter then picks it up 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.
151
• Phase 1:
– Create flow with FixedResource Class objects only (neglect
TaskExecuters).
• Phase 2:
– Add TaskExecuters: Operator, Transporter and Robot.
– Try adding a second Transporter to the rack.
• Phase 3:
– Add NetworkNode path to control the travel path of the
Transporters.
• Phase 4:
– Add a 3D pie chart to show the status of the Operator
– Add 3D text to show the content of the Rack
152
Model 3 Layout – Phase 1
153
• 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
154
• 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 the system
flowitems is in the OnEntry trigger of the Sink.
155
• The Queue is used to
stage FlowItems for
downstream operations.
• Queues are used in the
model wherever work-in-
process (WIP) exists
between process steps.
• A Queue may be a
table, basket, line, or
waiting room.
156
• Used to convey flowitems from one location in the
model to another location.
• Convey time 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!
157
• The FlowNode is used in a model where it is
desirable to have flowitems move along a
designated path to another object in the
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.
158
• 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 plus any Blocked Time. The dwell time
may also include time waiting for an operator,
time waiting for a transporter and time waiting for
the Processor to be repaired if broken down.
159
• 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 spot
where several operations are
performed before it moves again.
• Only 1 flowitem at a time is
allowed in the MultiProcessor.
160
• 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.
161
• 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.
163
164
Complete Phase 1
• Phase 1:
– Obtain flow with FixedResource Class objects only (neglect
TaskExecuters).
165
Model 3 Layout – Phase 2
166
• The Dispatcher receives tasksequences and either queues them up,
OR dispatches the tasksequences immediately to downstream
Dispatchers and/or TaskExecuters (single or team).
• One tasksequence may preempt another tasksequence part way
through the current one’s list of tasks. The preemption can either
temporarily interrupt the current tasksequence or permanently
destroy the current tasksequence and all sequences in queue.
• Tasksequences can be sorted by their priority.
• Tasksequences are created and dispatched automatically when the
“Use Transport” or “Use Operator” boxes are checked on a
FixedResource type object.
• Custom tasksequences can also be created and dispatched using
commands in triggers or elsewhere in your model. (taught later)
167
• TaskExecuters are subclasses of the
Dispatcher, and therefore can receive, queue
up, and dispatch tasksequences.
• In addition, TaskExecuters have the ability to
execute the tasksequences that they receive.
• The Operator, Transporter, Elevator, Robot,
Crane, and ASRSvehicle are all subclasses of
the TaskExecuter and therefore have similar
functionality.
168
• An Operator will model
human tasks such as
machine setup or manual
assembly.
• It 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.
169
• 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 another.
• The Transporter can travel in x, y and z directions.
• During offset travel the forks lift or lower in the z direction has
needed to pick or place flowitems.
• Transporters can load many FlowItems from multiple locations and
then unload the FlowItems separately to multiple locations.
170
171
Center Output
Dispatcher
TaskExecuter
172
Complete Phase 2
• Phase 2:
– Add TaskExecuters: Operator, Transporter and Robot.
– Try adding a second Transporter to the rack.
173
Model 3 Layout – Phase 3
174
• A NetworkNode is used to define the path a
TaskExecutor will follow when executing its travel tasks.
• A path is made up of a group of NetworkNodes
connected together by using the “A” key.
• At least one NetworkNode needs to be connected to
each load and unload station (FixedResource) using the
“A” key.
• A Task Executor is assigned to a path by connecting it
to any NetworkNode in the path using the “A” key.
175
• Click-and-drag a
connection while
pressing the “A” key
• When connected
you will see a green
path between the
nodes denoting
travel is allowed in
both directions.
176
• Click-and-drag a
connection while
pressing the “A” key
between the
NetworkNode and
the object where the
load takes place.
• A blue line will show
the connection. The
line does not
connect to any port.
177
Connecting a TaskExecutor
to a Path
• 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.
178
• A path can be restricted to
travel in a single direction
by pressing the “Q” key
and clicking-and-dragging
in the direction you want
to disallow travel.
• A red line (right side rule)
will show the restricted
direction.
179
• A non-passing path
can be defined by No traveling
using the “A” key
and click-and-
dragging between Travel but no passing
two nodes that are
already connected.
• Non-passing path
segments turn a
yellow color.
180
• Every path has a spline
point in the center of the
path by default.
• Spline points allow
paths to be curved.
• Add spline points by
pressing “X” and
clicking on an existing
spline point.
• Delete spline points by
selecting them and
pressing “Delete”
181
Hide Splines, Paths and
NetworkNodes
• The display options
for a path system
can be toggled by
holding the “X” key
down and then
clicking on any
NetworkNode in the
path system.
182
Complete Phase 3
• Phase 3:
– Add NetworkNode path to control the travel path of the
Transporters.
– Can you make the Transporters travel in a counter-clockwise
direction? 183
Model 3 Layout – Phase 4
184
• The Recorder is used to display and record
statistical information.
• The Recorder can display 3D charts and
graphs from object data or tables.
• Turn the object’s history “On” when you want
to display information (under Stats menu).
• Can gather point statistics (min, max, avg) or
complete historical data at set time intervals or
based on actual object events.
185
• 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.
186
Complete Phase 4
• Phase 4:
– Add a 3D pie chart to show the status of the Operator
– Add 3D text to show the content of the Rack
189
functionname(argument1, argument2, etc)
190
• 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 (ie { }) are used to define a block of statements.
• to comment the rest of a line use // and type note here
• don’t use spaces or special characters in name definitions
( _ is ok).
• names may include numbers, but may not begin with a number
(machine_9 is acceptable, 9machine is not).
191
• 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, gui’s and data.
192
• 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
193
Standard Folder
Object
Object data
Function (C++)
Function (FlexScript)
194
195
• int Integer (1, 2, 3, 14324)
• double double precision (2.5, 3.14159)
• string text string (“Anthony was here.”)
• fsnode* pointer to a Flexsim tree node
196
• int index = 1;
• double weight = 175.8;
• string category = “groceries”;
• fsnode* forklift = centerobject(current,1);
197
• x+y x plus y
• x-y x minus y
• x*y x times y
• x/y x divided by y
• sqrt(x) square root of x
• pow(x,y) x to the power of y (xy)
• round(x) x rounded to the nearest integer
• frac(x) returns the decimal portion of x
• fmod(x,y) returns the remainder of x/y
198
• x>y x greater than y
• x<y x less than y
• x >= y x greater than or equal to y
• x <= y x less than or equal to y
• x == y x equal to y
• x != y x not equal to y
• comparetext(string1,string2) string1 matches string2
199
• && logical AND
• || logical OR
• ! logical NOT
• min(x,y) returns minimum of x and y
• max(x,y) returns maximum of x and y
200
• x=y set x to y
• x += y set x to x plus y
• x -= y set x to x minus y
• x *= y set x to x times y
• x /= y set x to x divided by y
• x ++ add 1 to x
• x -- subtract 1 from x
201
• current - the current object, the owner of the code
• item - the involved flowitem that triggered the event
• model() point to model tree
• rank(node,ranknum) rank(current,3)
• inobject(object,portnum) inobject(current,1)
• outobject(object,portnum) outobject(current,1)
• centerobject(object,portnum) centerobject(current,1)
• node(“relativepath”,object)
node(“/Operator1”,model())
202
• content( object )
• getinput( object )
• getoutput( object )
203
• xloc( object ) yloc( object ) zloc( object )
• setloc( object, xnum, ynum, znum )
204
• itemtype – all flowitems have an attribute
called itemtype. It’s a numeric identifier used
to distinguish one “type” of flowitem from
another in processing and routing decisions in
a model.
205
• getname( object )
• setname( object, “name” )
• getitemtype( object )
• setitemtype( object, num)
• setcolor( object, red, green, blue )
• colorred( object ) – blue,green,random...
206
• Purpose
– Gain experience in writing C++ code in the Code Edit windows.
– Introduction to PROSESTART and PARAMSTART statements
and how they define the Code Template windows.
– Introduction to the bernoulli command.
bernoulli(num probability, num succeed-value, num fail-value, [num stream])
• Description
– See layout slide for model 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)
207
208
if (test expression) if (content(item) == 2)
{ {
code block colorred(item);
} }
else else
{ {
code block colorblack(item);
} }
209
• Purpose
– Learn how to both set and read the itemtype of a flowitem
using C++
• Description
– See layout slide for model description.
– 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?
210
• labels – information may
also be stored on
flowitems (and other
modeling objects) in the
form of labels. You may
define as many labels on
a flowitem or object as
you would like. Labels
have a name and data.
The data may be
numeric, string, list, or
table
211
• syntax
– 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 ) only works with number data nodes
212
switch ( switchvariable ) int type = getitemtype(item);
{ switch (type)
case casenum: {
case 1:
{ {
code block coloryellow(item);
break;
break; }
} case 5:
{
default: colorred(item);
break;
{ }
code block default:
{
break; colorgreen(item);
} break;
} 213
} }
• Purpose
– Learn how to both set and read the labels on a flowitem using
C++
• Description
– See layout slide for model description.
– 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
• Label values 1 and 3 go to port 2
• Label values 2 and 4 go to port 1
• Questions
– Can you change the color of the flowitems based on their label
using code?
214
while (test expression) while (content(current) > 0)
{ {
code block destroyobject(last(current));
} }
215
for (start expression; for (int index = 1;
test expression; index <= content(current);
count expression) index++)
{ {
code block colorblue(rank(current,index));
} }
216
• Purpose
– Learn how to write your own “for” loop.
• Description
– A Combiner packs 8 boxes on a pallet.
– Use an infinite supply of pallets from one Source and an infinite supply
of boxes from another Source.
– The Combiner sends to a Conveyor which then sends to another
Conveyor.
– Using the OnExit trigger of the first Conveyor, write a for loop which
changes the color of all the boxes on the pallet.
• Questions
– Can you change the 3D shapes of the boxes on the pallet with the
setobjectshapeindex() picklist to a tote?
217
218
Concepts and Models
• Itemtypes
• Push vs. Pull
• Distributions (continuous vs. discrete)
220
• Purpose
– Learn how to use pull logic in defining routings based on a
flowitem’s itemtype.
• Description
– Electronic components need to be tested after manufacture.
– There are two types of components that arrive in a queue at
random with the mix being 40% of one and 60% the other.
– The inter-arrival time of components is exponential(0,30,1)
– There are two testers for component 1 and three testers for
component 2. Components will go to the first available tester.
– Testing times are all between 120 and 150 seconds uniformly
distributed.
• Questions
– Are all testers equally utilized?
– Can you model this with push or pull?
– Try assigning colors to the itemtypes. 221
222
• Labels and Itemtypes
• Empirical Distributions ~ Global Tables
• Trigger sequence
223
• Purpose
– Learn how to assign and use labels on flowitems for routing and
processing purposes. Learn how to use an empirical distribution to
assign itemtypes.
• Description
– Parts arrive in a queue every 30 seconds exponentially distributed.
There are four part types (1,2,3,4) distributed (20%, 30%, 40%, 10%)
respectively.
– The four part types are each processed on one of four dedicated
machines. The processing times at each machine is uniform(100,120)
seconds for first time parts, and uniform(120,130) seconds for rework
parts.
– After the parts are machined, they are put in a queue and wait to be
tested. The test time is a constant 10 seconds. Parts that pass, leave
the model, failed parts are routed back to the first queue to be
reworked. 10% of the parts fail.
– Parts being reworked are given priority in the queue.
• Questions
– Where is the bottleneck?
– Can you change the color and shape of failed parts?
224
Model 5 Layout
225
• Global Tables
• Labels
• Triggers
226
• gettablenum( “tablename”, rownum, colnum )
• settablenum( “tablename”, rownum, colnum, value )
• gettablestr( “tablename”, rownum, colnum )
• settablestr( “tablename”, rownum, colnum, string )
227
• Purpose
– Small example of using a Global Table to define product routings.
– Learn how to use a label to keep track of what step the flowitem is on.
• Description
– 3 different products (uniform) enter a 5 station work cell.
– Product 1 needs to be processed at station 1,3, and 2.
– Product 2 needs to be processed at station 1, 2, and 4.
– Product 3 need to be processed at station 2,4,3, and 5.
– Use a global table to make sure the products are sent to the right
station in the proper sequence.
– Use a single Queue whose output ports are connected to each of the 5
stations and to a Sink. Each of the five stations have their output port
also connected to the input ports of the Queue.
• Questions
– Can you change all flowitems in the model to a common color
depending on step?
228
229
• TaskSequence Priority
• Global Pointers
230
• Purpose
– Learn how to us an Operator to both carry and process
flowitems
• Description
– Parts arrive at a queue every 20 seconds exponentially
distributed and need to be carried by the operator to one of the
3 first available machines.
– The operator needs to setup the part which takes 10 seconds.
– The part will then process for 20 seconds on its own.
– When the part finishes, it will leave the system.
– One operator will run all three machines.
• Questions
– See if you can get the operator to stay for setup once he has
carried the product to the machine.
– Can you create the same model without center port
connections?
231
232
• Send To Port
• “Break To” Requirement
233
• Purpose
– Learn how to use the “Break To” Requirement field on
TaskExecuters.
• Description
– A Source continuously sends Flowitems randomly to 3 Queues.
– Flowitems are assigned an itemtype 1,2,3 uniformly distributed.
– All three Queues can hold all three itemtypes.
– A Transporter carries Flowitems to three Queues that each hold 1
itemtype.
– These Queues then go to Processors and a Sink.
– The Transporter can carry up to 5 items at a time.
– The Transporter should only carry items that have the same itemtype
at any time.
• Questions
– Experiment with the other available “Break To” Requirement pick-
options. How does the Transporter behave?
234
235
• TaskExecuter Teams
• TaskSequence Preemption
• Time Tables
236
• Purpose
– More practice working with teams, priorities and preempting
• Description
– A single work cell has 5 machines.
– Each part must be processed at each of the 5 machines
– There are 3 operators who work in the cell as a team.
– The operators need to carry each part to the next machine as
well as set up the machine for that part.
– Setup times are 5 seconds and process times are 15.
– New parts arrive in the system every 25 seconds.
• Questions
– What’s the throughput rate per hour?
– Experiment with priorities and preempting to try and improve the
throughput rate.
– Assign each operator to a different timetable so their breaks and
lunches are staggered.
237
238
• Update Combiner Component List OnEntry
• Excel Imports and Exports ~ Multi-Table
239
Example:
excellaunch(“ C:\Program Files\Microsoft Office\Office10”);
excelopen(“C:\mybook.xls”);
excelsetsheet(“Sheet1”);
double thenum = excelreadnum(1,1);
excelwritenum(5,2,thenum)
excelclose(true);
excelquit();
This starts Excel, opens a workbook called “mybook,” and stores a value read from
row 1, column 1 from Sheet1, then writes the stored value to row 5, column 2. Excel
is then closed.
See also excelimporttable() and excelimporttable()
Rules:
Excel must be opened using excellaunch() before excelopen() is called. Only one
workbook can be open at a time. The use still must call excelclose() before trying to
open another workbook. Before reading from the open file, excelsetsheet() must
also be called to point to the appropriate worksheet.
240
• Purpose
– Learn how to manipulate the Components List table on a
Combiner object to do custom packing on the fly
– Learn how to import and use a Source arrival schedule
• Description
– A small distributor has 10 product types that he ships to the
same 5 customers.
– Each customer has a different order profile.
– The distributer has a large supply of each of the 10 products
so all he has to do is wait for an order to come through the
door.
– Products are placed on a pallet and then conveyed out.
– Use the next two tables to build the model.
• Questions
– Can you think of other uses for the Combiner?
– If time permits, try importing the tables from Excel.
241
242
Model 10 Order Table
243
Model 10 Daily Arrival Schedule
Customer 1 0 OrderA 1 1
244
More Advanced Concepts and
Models…
• Abstract Model Application
• Global Object Pointers
• For Loop
• moveobject() command
246
• Purpose
– Gain experience in building an abstract model
– Learn to write some C++ in a trigger field
• Description
– Items arrive at a warehouse each day to be stored.
– Orders arrive at a warehouse each day to be pulled.
– The average number of items and orders received each day is 10, but both are
exponentially distributed.
– There are only 5 types of items (and therefore orders) received. The type of
received items and orders is uniformly distributed 1 through 5 on a daily basis.
– Whenever an order arrives it must search for a matching item and remove it.
– Whenever an item arrives it must search for a matching order and remove it.
– 1 model time unit = 1 day.
• Questions
– How big must the warehouse be, so there is always room to store the items
received each day?
– Plot the number of unsatisfied orders each day for an entire year.
– What’s the average number of days an order waits to be satisfied?
247
Model A1 Layout
248
• Custom TaskSequences
• Global Pointers
249
• Simple Commands
requestoperators( taskexecuter, station, involvedobj, nrofops, priority,
preempting )
freeoperators( taskexecuter, involvedobj )
dispatchtasksequence(ts);
251
TASKTYPE_LOAD: flowitem, pickup
TASKTYPE_FRLOAD: flowitem, pickup, [outputport]
TASKTYPE_UNLOAD: flowitem, dropoff
TASKTYPE_FRUNLOAD: flowitem, dropoff, [inputport]
TASKTYPE_UTILIZE: involved, station, [state]
TASKTYPE_STOPREQUESTFINISH: stoppedobject, NULL
TASKTYPE_TRAVEL: destination, NULL
TASKTYPE_TRAVELTOLOC: NULL, NULL, [xloc,yloc,zloc,endspeed]
TASKTYPE_TRAVELRELATIVE: NULL, NULL, [xloc,yloc,zloc,endspeed]
TASKTYPE_BREAK: NULL, NULL
TASKTYPE_DELAY: NULL, NULL, [delaytime, state]
TASKTYPE_SENDMESSAGE: receiver, NULL, [param1,param2,param3]
TASKTYPE_MOVEOBJECT: flowitem, container, [port]
TASKTYPE_DESTROYOBJECT: object, NULL
Brown parameters are required, [Gray] parameters are optional
** use profiletasksequence(ts) to print to console full description of ts
252
• Purpose
– Learn how to manually build your own tasksequences
• Description
– The model consists of a Source, three Processors in series,
and a Sink.
– An operator must pick up a part from the source, carry it to the
first processor, be utilized for the process time, carry the part
to the next processor, etc. until finally dropping it off at the sink.
– Use Global Object Pointers instead of center port connections.
• Questions
– How many operators does it take to make 1000 pieces a day?
253
Model A2 Layout
254
• Closing and Opening Output/Input Ports
• Message Sending
• Stop and Resume commands
255
• closeinput( object ), openinput( object )
• stopinput( object ), resumeinput( object )
• closeoutput( object ), openoutput( object )
• stopoutput( object ), resumeoutput( object )
• sendmessage( toobject, fromobject, parameter1, parameter2,
parameter3 )
• senddelayedmessage( toobject, delaytime, fromobject,
parameter1, parameter2, parameter3 )
• stopobject( object ), resumeobject( object )
• moveobject( object, containerobject )
256
• message – information sent from one
object to another. When the message is
received, a trigger is fired. A message is
sent with a command. Messages may be
sent immediately sendmessage(), or after
a specified period of time
senddelayedmessage().
257
• Purpose
– Learn how to control product flow and send delayed messages.
• Description
– Assume an infinite supply of A and B components.
– The two components must be glued together with epoxy which
takes lognormal(0,2.6,0.8) seconds.
– The assembled parts must wait in a staging area for at least 15
seconds for the epoxy to cure before they can enter the paint
booth.
– It takes lognormal(0,2.5,0.5) seconds to paint each part
separately.
– After each part is painted and exits the paint booth, the booth
must be purged for 3 seconds before another part can enter.
• Questions
– What is the average and maximum time a part waits in queue?
258
259
• TrafficControl Object
• TaskExecuter Collision Tab
• Experimenter
• Presentation Builder
• ExpertFit
260