PadhaikoAll subjects

Simulation software

Simulation and Modeling (ENCT 353)

Open in the Padhaiko app

9.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


9.2 Simulation in GPSS

Definition

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

Core GPSS Block Statements
Block / StatementSyntax ExampleFunction
GENERATEGENERATE 10,3Creates transactions with inter-arrival time uniformly distributed in (i.e., )
QUEUEQUEUE LINE1Increments waiting-line counter and records wait-start time for queue LINE1
SEIZESEIZE TELLERAcquires single-server Facility TELLER (blocks transaction on CEC if busy)
DEPARTDEPART LINE1Leaves waiting-line statistics for LINE1 once service begins
ADVANCEADVANCE 8,2Delays transaction on the FEC for service time (i.e., )
RELEASERELEASE TELLERFrees Facility TELLER so the next waiting transaction can seize it
ENTER / LEAVEENTER BOOTHS,1 / LEAVE BOOTHS,1Acquires/releases units of a multi-server Storage (defined by BOOTHS STORAGE 3)
TRANSFERTRANSFER 0.2,,REJECTProbabilistic branching ( jump to label REJECT, fall through)
TERMINATETERMINATE 1Destroys transaction and decrements the simulation termination counter by
STARTSTART 500Sets 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:


9.4 Other simulation software

Comparison of Widely Used Simulation Software Packages
SoftwareModeling ParadigmPrimary Application DomainsKey Strength
Arena (Rockwell)Flowchart-based DES (built on SIMAN)Manufacturing, logistics, healthcare, supply chainsDrag-and-drop modules, built-in Input/Output Analyzer, 2D/3D animation
AnyLogicMulti-method (DES + Agent-Based + System Dynamics)Pedestrian flow, supply networks, urban trafficCombines continuous stocks, agents, and discrete queues in one model
MATLAB / SimulinkBlock-diagram continuous & hybrid solversControl systems, signal processing, aerospace, HILTight integration with ODE solvers (RK45, stiff solvers) and code generation
NS-3 / OMNeT++Packet-level discrete-event network simulationTCP/IP routing, 5G wireless, IoT protocolsAccurate MAC/PHY protocol stacks and packet trace PCAP export
FlexSim / ProModel3D object-oriented DESSmart factories, automated warehouses, material handlingNative 3D CAD layout and conveyor/AGV physics
AspectGeneral-Purpose Languages (Java / Python)Dedicated Simulation Tools (GPSS / Arena)
Modeling FlexibilityUnlimited; custom data structures and algorithmsConstrained by built-in blocks unless extended via scripts
Development SpeedSlower; must build or wire statistics/animationRapid; queues, resources, and summary reports are built in
Execution Speed & CostFast (especially Java/C++), free open-sourceCommercial licenses costly (Arena/AnyLogic); high productivity

Worked Out Examples

Example 1

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:

Java Single-Server M/M/1 Discrete-Event SimulatorJava
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);
    }
}
Answer:

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.

Example 2

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,2 creates customer transactions at intervals uniform on .
  • QUEUE COUNTER and DEPART COUNTER bracket SEIZE TICKET to measure queuing delay.
  • ADVANCE 5,1 holds the server for uniform before RELEASE TICKET frees it.
  • TERMINATE 1 counts completed customers down from START 200.
GPSS Single-Server Ticket Counter ModelText
         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
         END

Interpreting GPSS Standard Report Metrics:

  • Under FACILITIES (TICKET), UTIL. gives the fraction of total clock time the server was seized (), and AVERAGE TIME/TRAN reports mean service duration ().
  • Under QUEUES (COUNTER), MAX gives peak queue length, AVERAGE CONT. gives , PERCENT ZEROS gives the percentage of customers who waited time, and AVERAGE TIME/TRANS gives .
Answer:

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).

Example 3

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:

Python SimPy M/M/2 Bank Branch SimulationPython
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()
Answer:

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

Question 1

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.
Answer:

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.

Question 2

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 SEIZE and RELEASE.
  • A Storage represents a multi-server resource pool of identical units (declared via NAME STORAGE k), controlled by ENTER and LEAVE.

CEC vs. FEC:

  • FEC (Future Event Chain): Holds transactions scheduled to move at a future clock time (from GENERATE or ADVANCE), 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 SEIZE a busy facility or ENTER a full storage).
Answer:

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.

Question 3

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:

GPSS Two-Mechanic Workshop ModelText
         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
         END
Answer:

Declare 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.

Question 4

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 clock env.now.
  • Generator Processes (yield): Active entities are Python generator functions registered via env.process(...). Whenever a generator executes yield env.timeout(d), SimPy suspends that function and schedules a resume event at env.now + d.
  • simpy.Resource(env, capacity=c): Manages server slots; yield req suspends the process if all slots are occupied and wakes it automatically in FIFO order when another process exits its with block.
Answer:

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.

Question 5

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.
Answer:

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.

← Analysis of simulation outputSimulation of Computer Systems →