Simulation software
Open in the Padhaiko app9.1 Simulation in Java
Using a general-purpose object-oriented language like Java gives the analyst complete flexibility over event structures, memory, and custom scheduling policies without the licensing cost or rigid blocks of commercial tools.
Key Java Constructs for Discrete-Event Simulation
- Entities & Events as Classes: Each entity (e.g.,
Customer,Packet) encapsulates its arrival timestamp and attributes, while eachEventimplementsComparable<Event>ordered byeventTime. - Future Event List (FEL): Implemented cleanly using
java.util.PriorityQueue<Event>(a binary min-heap giving insertion and extraction of the next imminent event). - Queue Buffers: Implemented using
java.util.ArrayDeque<Customer>(FIFO) or a secondaryPriorityQueue(priority scheduling). - Random Variates:
java.util.Random(seed)orSplittableRandomproduces reproducible draws vianextDouble(), transformed into Exponential () or Normal (nextGaussian()) variates. - Dedicated Java Simulation Libraries: SSJ (Stochastic Simulation in Java), SimKit, and MASON (multi-agent simulation).
9.2 Simulation in GPSS
General Purpose Simulation System (GPSS)
GPSS (developed by Geoffrey Gordon at IBM) is a transaction-flow (process-oriented) discrete-event simulation language. Temporary entities called transactions (customers, parts, messages) are created, move sequentially through a flowchart of blocks representing delays and resources, and are destroyed upon exit—while GPSS automatically maintains the simulation clock, Future Event Chain (FEC), Current Event Chain (CEC), and summary statistics.
Essential GPSS Blocks
| Block / Statement | Syntax Example | Function |
|---|---|---|
GENERATE | GENERATE 10,3 | Creates transactions with inter-arrival time uniformly distributed in (i.e., ) |
QUEUE | QUEUE LINE1 | Increments waiting-line counter and records wait-start time for queue LINE1 |
SEIZE | SEIZE TELLER | Acquires single-server Facility TELLER (blocks transaction on CEC if busy) |
DEPART | DEPART LINE1 | Leaves waiting-line statistics for LINE1 once service begins |
ADVANCE | ADVANCE 8,2 | Delays transaction on the FEC for service time (i.e., ) |
RELEASE | RELEASE TELLER | Frees Facility TELLER so the next waiting transaction can seize it |
ENTER / LEAVE | ENTER BOOTHS,1 / LEAVE BOOTHS,1 | Acquires/releases units of a multi-server Storage (defined by BOOTHS STORAGE 3) |
TRANSFER | TRANSFER 0.2,,REJECT | Probabilistic branching ( jump to label REJECT, fall through) |
TERMINATE | TERMINATE 1 | Destroys transaction and decrements the simulation termination counter by |
START | START 500 | Sets termination counter to and executes the simulation |
9.3 Simulation in Python
Python has become a leading environment for both academic and industrial simulation because of its concise syntax and rich scientific ecosystem:
- SimPy (Process-Based DES): Uses Python generator functions (
yield env.timeout(dt),yield req) to model active entities (customers, packets, vehicles) cleanly without manually coding event-list heaps.simpy.Environment(): Manages the simulation clock and event queue.simpy.Resource(env, capacity=c): Models parallel servers with automatic FIFO queuing.simpy.Store/simpy.Container: Models bounded buffers and continuous material tanks.
- Monte-Carlo and Continuous Simulation: Standard
random.Random(seed)handles reproducible PRNG streams; NumPy vectorizes millions of Monte-Carlo trials; SciPy (scipy.integrate.solve_ivp) integrates stiff and non-stiff continuous ODE systems.
9.4 Other simulation software
| Software | Modeling Paradigm | Primary Application Domains | Key Strength |
|---|---|---|---|
| Arena (Rockwell) | Flowchart-based DES (built on SIMAN) | Manufacturing, logistics, healthcare, supply chains | Drag-and-drop modules, built-in Input/Output Analyzer, 2D/3D animation |
| AnyLogic | Multi-method (DES + Agent-Based + System Dynamics) | Pedestrian flow, supply networks, urban traffic | Combines continuous stocks, agents, and discrete queues in one model |
| MATLAB / Simulink | Block-diagram continuous & hybrid solvers | Control systems, signal processing, aerospace, HIL | Tight integration with ODE solvers (RK45, stiff solvers) and code generation |
| NS-3 / OMNeT++ | Packet-level discrete-event network simulation | TCP/IP routing, 5G wireless, IoT protocols | Accurate MAC/PHY protocol stacks and packet trace PCAP export |
| FlexSim / ProModel | 3D object-oriented DES | Smart factories, automated warehouses, material handling | Native 3D CAD layout and conveyor/AGV physics |
| Aspect | General-Purpose Languages (Java / Python) | Dedicated Simulation Tools (GPSS / Arena) |
|---|---|---|
| Modeling Flexibility | Unlimited; custom data structures and algorithms | Constrained by built-in blocks unless extended via scripts |
| Development Speed | Slower; must build or wire statistics/animation | Rapid; queues, resources, and summary reports are built in |
| Execution Speed & Cost | Fast (especially Java/C++), free open-source | Commercial licenses costly (Arena/AnyLogic); high productivity |
Worked Out Examples
1
Write a clean Java discrete-event simulation program (using PriorityQueue for the Future Event List) that simulates a single-server queue for customer arrivals with arrival rate and service rate , and reports the simulated server utilization and average waiting time.
Defining the Event class and exponential variate helper: Events are ordered chronologically by time via Comparable<Event>. Exponential inter-arrival and service times are generated using inverse transform .
Implementing the event-scheduling loop in Java:
import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class MM1Simulator {
enum Type { ARRIVAL, DEPARTURE }
static class Event implements Comparable<Event> {
double time;
Type type;
Event(double time, Type type) {
this.time = time;
this.type = type;
}
@Override
public int compareTo(Event other) {
return Double.compare(this.time, other.time);
}
}
static double expVariate(Random rng, double rate) {
return -Math.log(1.0 - rng.nextDouble()) / rate;
}
public static void main(String[] args) {
double lambda = 4.0, mu = 5.0;
int maxCustomers = 1000;
Random rng = new Random(42L);
PriorityQueue<Event> fel = new PriorityQueue<>();
Queue<Double> waitQueue = new ArrayDeque<>();
double clock = 0.0, lastEventTime = 0.0;
boolean serverBusy = false;
double totalBusyTime = 0.0, totalWaitTime = 0.0;
int arrived = 0, served = 0;
fel.add(new Event(expVariate(rng, lambda), Type.ARRIVAL));
while (!fel.isEmpty() && served < maxCustomers) {
Event ev = fel.poll();
clock = ev.time;
if (serverBusy) {
totalBusyTime += (clock - lastEventTime);
}
lastEventTime = clock;
if (ev.type == Type.ARRIVAL) {
arrived++;
if (arrived < maxCustomers) {
fel.add(new Event(clock + expVariate(rng, lambda), Type.ARRIVAL));
}
if (!serverBusy) {
serverBusy = true;
fel.add(new Event(clock + expVariate(rng, mu), Type.DEPARTURE));
} else {
waitQueue.add(clock);
}
} else {
served++;
if (!waitQueue.isEmpty()) {
double arrivalTime = waitQueue.poll();
totalWaitTime += (clock - arrivalTime);
fel.add(new Event(clock + expVariate(rng, mu), Type.DEPARTURE));
} else {
serverBusy = false;
}
}
}
System.out.printf("Utilization: %.4f%n", totalBusyTime / clock);
System.out.printf("Mean Queue Wait: %.4f hr%n", totalWaitTime / served);
}
}The Java program uses a PriorityQueue<Event> as the FEL and an ArrayDeque<Double> to record waiting customer arrival timestamps. Whenever an event pops, totalBusyTime accumulates over (clock - lastEventTime), and ARRIVAL/DEPARTURE handlers schedule future events until departures complete.
2
Write a GPSS program to simulate a single-server ticket counter where customers arrive every minutes and service takes minutes. Simulate until customers complete service, and explain how GPSS computes facility utilization and average queue wait from its output report.
Writing the GPSS block sequence:
GENERATE 6,2creates customer transactions at intervals uniform on .QUEUE COUNTERandDEPART COUNTERbracketSEIZE TICKETto measure queuing delay.ADVANCE 5,1holds the server for uniform beforeRELEASE TICKETfrees it.TERMINATE 1counts completed customers down fromSTART 200.
SIMULATE
GENERATE 6,2 ; Customer arrives every 6 +/- 2 min
QUEUE COUNTER ; Join waiting line statistics
SEIZE TICKET ; Acquire single ticket counter
DEPART COUNTER ; Leave queue stats upon starting service
ADVANCE 5,1 ; Service time 5 +/- 1 min
RELEASE TICKET ; Free the ticket counter
TERMINATE 1 ; Exit system and count 1 completion
START 200 ; Stop after 200 customers depart
ENDInterpreting GPSS Standard Report Metrics:
- Under FACILITIES (
TICKET),UTIL.gives the fraction of total clock time the server was seized (), andAVERAGE TIME/TRANreports mean service duration (). - Under QUEUES (
COUNTER),MAXgives peak queue length,AVERAGE CONT.gives ,PERCENT ZEROSgives the percentage of customers who waited time, andAVERAGE TIME/TRANSgives .
The GPSS model uses GENERATE 6,2, QUEUE COUNTER, SEIZE TICKET, DEPART COUNTER, ADVANCE 5,1, RELEASE TICKET, TERMINATE 1, and START 200. GPSS automatically prints Facility utilization () and Queue statistics (, zero-wait fraction).
3
Write a Python (SimPy) program to simulate a two-teller bank branch () with mean inter-arrival time () and mean service time () for a -minute workday, recording customer waiting times.
Modeling customer processes and the simpy.Resource pool: Each customer is a generator customer(env, tellers, waits) that requests one teller with with tellers.request() as req: yield req, logs env.now - arrival, and holds the teller for rng.expovariate(1.0 / 8.0).
Complete SimPy implementation:
import random
import simpy
def customer(env, tellers, rng, waits):
arrival_time = env.now
with tellers.request() as req:
yield req
waits.append(env.now - arrival_time)
service_time = rng.expovariate(1.0 / 8.0)
yield env.timeout(service_time)
def arrival_generator(env, tellers, rng, waits):
while True:
yield env.timeout(rng.expovariate(1.0 / 5.0))
env.process(customer(env, tellers, rng, waits))
def run_bank_sim(seed=7, horizon=480.0):
rng = random.Random(seed)
env = simpy.Environment()
tellers = simpy.Resource(env, capacity=2)
waits = []
env.process(arrival_generator(env, tellers, rng, waits))
env.run(until=horizon)
avg_wait = sum(waits) / len(waits) if waits else 0.0
print(f"Served: {len(waits)}, Mean Wait: {avg_wait:.3f} min")
if __name__ == "__main__":
run_bank_sim()The SimPy script models parallel tellers using simpy.Resource(env, capacity=2) and schedules arrivals/service times using yield env.timeout(...) over a -minute horizon, collecting exact per-customer waiting delays in waits.
Exercises
Practice Exercises — Simulation Software
Compare general-purpose programming languages (such as Java and Python) with dedicated simulation software (such as GPSS and Arena) across flexibility, development effort, built-in statistics, and cost.
Comparison Criteria:
- Flexibility: Java/Python allow arbitrary custom algorithms, routing rules, and data structures; GPSS/Arena rely on predefined block templates.
- Development Effort & Statistics: GPSS/Arena provide automatic clock management, FEL/CEC scheduling, queue statistics, and animation out of the box; Java/Python require coding event loops and statistical accumulators (unless using SimPy/SSJ).
- Cost & Portability: Java and Python are free, open-source, and cross-platform; commercial packages like Arena carry high licensing fees.
Java/Python provide unlimited modeling flexibility and zero licensing cost, whereas GPSS/Arena accelerate standard queuing/factory modeling with built-in event engines, automatic statistical reports, and visual animation.
Explain the transaction-flow paradigm of GPSS, distinguishing between a Facility and a Storage, and between the Current Event Chain (CEC) and Future Event Chain (FEC).
Facility vs. Storage:
- A Facility represents a single-server resource (capacity ), controlled by
SEIZEandRELEASE. - A Storage represents a multi-server resource pool of identical units (declared via
NAME STORAGE k), controlled byENTERandLEAVE.
CEC vs. FEC:
- FEC (Future Event Chain): Holds transactions scheduled to move at a future clock time (from
GENERATEorADVANCE), sorted chronologically by departure/arrival timestamp. - CEC (Current Event Chain): Holds transactions ready to move at the current clock time (including blocked transactions waiting to
SEIZEa busy facility orENTERa full storage).
In GPSS, a Facility models a single server (SEIZE/RELEASE) while a Storage models a multi-unit pool (ENTER/LEAVE). The FEC stores timed future events sorted by clock time, whereas the CEC holds transactions active or blocked at the current instant.
Write a GPSS model for a repair workshop with two identical mechanics (a Storage named MECH of capacity ). Broken machines arrive every minutes, wait in queue REPAIRQ, take minutes to repair, and completed repairs end the run.
Declaring the Storage and transaction flow: Declare MECH STORAGE 2 at the top, use ENTER MECH and LEAVE MECH in place of SEIZE/RELEASE, and bracket with QUEUE REPAIRQ / DEPART REPAIRQ.
Complete GPSS program:
SIMULATE
MECH STORAGE 2 ; Pool of 2 identical mechanics
GENERATE 12,4 ; Broken machine arrives every 12 +/- 4 min
QUEUE REPAIRQ ; Record entry into repair queue
ENTER MECH ; Acquire 1 available mechanic
DEPART REPAIRQ ; Exit queue statistics
ADVANCE 18,5 ; Repair duration 18 +/- 5 min
LEAVE MECH ; Free the mechanic
TERMINATE 1 ; Completed repair
START 100 ; Simulate 100 repairs
ENDDeclare MECH STORAGE 2 and route GENERATE 12,4 transactions through QUEUE REPAIRQ, ENTER MECH, DEPART REPAIRQ, ADVANCE 18,5, LEAVE MECH, and TERMINATE 1 with START 100.
Explain how SimPy implements discrete-event simulation in Python using generator functions (yield), simpy.Environment, and simpy.Resource.
Role of SimPy Core Components:
simpy.Environment(): Maintains the internal priority-heap event list and current simulation clockenv.now.- Generator Processes (
yield): Active entities are Python generator functions registered viaenv.process(...). Whenever a generator executesyield env.timeout(d), SimPy suspends that function and schedules a resume event atenv.now + d. simpy.Resource(env, capacity=c): Manages server slots;yield reqsuspends the process if all slots are occupied and wakes it automatically in FIFO order when another process exits itswithblock.
SimPy simulates concurrency via lightweight Python generators (yield) managed by simpy.Environment()'s event heap, while simpy.Resource handles server capacity limits and automatic FIFO queuing.
Briefly describe the primary purpose and modeling paradigm of Arena, AnyLogic, MATLAB/Simulink, and NS-3 in engineering simulation.
Overview of Four Major Packages:
- Arena: Flowchart-driven discrete-event simulator widely used in manufacturing, service operations, and supply-chain analysis.
- AnyLogic: Multi-method platform uniting discrete-event, agent-based, and system-dynamics modeling in one environment.
- MATLAB / Simulink: Block-diagram continuous and hybrid simulation environment tailored for control loops, aerospace, and signal processing.
- NS-3: Open-source C++/Python packet-level discrete-event simulator built specifically for wired and wireless computer network protocols.
Arena focuses on flowchart DES for operations; AnyLogic combines DES, agent-based, and system dynamics; Simulink models continuous/hybrid control systems; and NS-3 simulates packet-level computer networks.