Data Analysis and ModelingUnit 1017 min read
Simulation Models: Types, Applications & Worked Examples
Unit 10 of Data Analysis and Modeling explores simulation models—how to replicate real-world systems (queues, supply chains, financial risks) using probability, random variables, and computational tools. Learn discrete-event, Monte Carlo, and system dynamics simulations, with step-by-step examples (e.g., Pathao driver
What is a Simulation Model?
A simulation model is a computational representation of a real-world system that mimics its behavior over time using random variables, probability distributions, and logical rules. Unlike analytical models (e.g., equations), simulations approximate complex systems where exact solutions are impractical.
Key Characteristics:
- Dynamic: Models systems that evolve over time (e.g., traffic flow, inventory levels).
- Stochastic: Uses randomness (e.g., customer arrival times, machine failures) via probability distributions.
- Replicable: Runs multiple scenarios to analyze outcomes (e.g., "What if 20% more customers arrive?").
- Visualizable: Often represented as state-space diagrams (networks of states and transitions) or timelines.
Types of Simulation Models
Simulations are classified based on their approach and application. Below are the three primary types covered in the syllabus:
1. Discrete-Event Simulation (DES)
Definition: Models systems where events (e.g., arrivals, departures, failures) change the system state at specific points in time. Time advances only when an event occurs.
How It Works:
- Events: Instantaneous occurrences (e.g., a customer entering a queue, a machine breaking down).
- State Variables: Track system status (e.g., number of customers in a queue, inventory levels).
- Clock: Advances only at event times (not continuously).
Example: Modeling Pathao driver wait times in Kathmandu.
- Events:
- Customer requests arrive (Poisson process, λ = 5 requests/hour).
- Drivers accept/reject requests (probability p = 0.7).
- Trip completes (exponential time, μ = 10 trips/hour).
- State Variable: Number of idle drivers.
- Output: Average wait time per customer.
flowchart LR
A["Start"] --> B["Customer arrives\n(Poisson, λ=5)"]
B --> C["Driver accepts\n(p=0.7)"]
C --> D["Trip starts\n(Exponential, μ=10)"]
D --> E["Trip ends\nDriver available"]
E --> B
C -->|"Reject"| F["Driver remains idle"]
F --> BAdvantages:
- Handles complex, irregular systems (e.g., hospitals, call centers).
- Easy to validate with real data.
Disadvantages:
- Requires careful event scheduling.
- Computationally intensive for large systems.
2. Monte Carlo Simulation
Definition: Uses random sampling to model uncertainty in systems where outcomes are probabilistic (e.g., financial risks, project delays).
How It Works:
- Define input variables with probability distributions (e.g., stock returns ~ Normal(μ, σ)).
- Generate random samples for each variable.
- Run the model thousands of times to estimate outcomes (e.g., "What’s the 95% confidence interval for project cost?").
Example: NEPSE stock price simulation for a Nepalese investor.
- Inputs:
- Current price: ₹1000.
- Daily return: Normal(0.1%, 2%) (mean daily gain of 0.1%, volatility of 2%).
- Simulation Steps:
- Generate 1000 random daily returns.
- Calculate price after 30 days for each scenario.
- Plot distribution of final prices.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
daily_returns = np.random.normal(0.001, 0.02, 1000) # μ=0.1%, σ=2%
final_prices = 1000 * np.cumprod(1 + daily_returns)
plt.hist(final_prices[-1], bins=30, edgecolor='k')
plt.title("NEPSE Price After 30 Days (Monte Carlo)")
plt.xlabel("Price (₹)")
Output:
Advantages:
- Captures uncertainty in inputs (e.g., interest rates, demand).
- Used in finance (option pricing), engineering (risk analysis), and healthcare (trial simulations).
Disadvantages:
- Results are probabilistic, not deterministic.
- Requires many iterations for accuracy.
3. System Dynamics Simulation
Definition: Models feedback loops and stock-flow relationships in systems (e.g., supply chains, ecosystems, economies). Focuses on how information and resources flow over time.
Key Concepts:
- Stocks: Accumulations (e.g., inventory, population, money in a bank).
- Flows: Rates of change (e.g., orders placed, births/deaths, interest earned).
- Auxiliary Variables: Supporting calculations (e.g., demand forecasts).
- Feedback Loops:
- Balancing: Self-correcting (e.g., more inventory → slower ordering).
- Reinforcing: Exponential growth (e.g., viral marketing).
Example: Daraz Nepal’s Inventory Management.
- Stock: Unsold smartphones (initial = 500 units).
- Flows:
- Orders received: 100 units/day (constant).
- Sales: Normal(80, 10) units/day (mean 80, σ=10).
- Feedback:
- If stock < 100 → reorder (reinforcing loop).
- If stock > 300 → discount sales (balancing loop).
flowchart TD
A["Stock: Unsold Phones\n(Initial=500)"] -->|"Flow"| B["Sales\n(Normal(80,10))"]
A -->|"Flow"| C["Orders\n(100/day)"]
B -->|"If Stock < 100"| D["Reorder\n(Trigger)"]
C -->|"If Stock > 300"| E["Discount\n(Balancing)"]
D --> A
E --> AAdvantages:
- Models long-term trends (e.g., population growth, business cycles).
- Visualizes cause-and-effect relationships.
Disadvantages:
- Complex to build (requires system mapping).
- Less precise for short-term tactical decisions.
## In the Real World
Simulation models are everywhere in Nepal’s digital and physical infrastructure. Here’s how companies and services use them:
Pathao/Khalti (Ride-Hailing & Payments)
- Discrete-Event Simulation: Models driver-customer matching to optimize wait times.
- Example: Simulate 10,000 rides in Kathmandu to find the ideal number of drivers per km².
- Output: Reduces empty rides by 15% (real-world test in 2022).
- Discrete-Event Simulation: Models driver-customer matching to optimize wait times.
Ncell/NTC (Telecom Networks)
- System Dynamics: Simulates network congestion during festivals (e.g., Dashain).
- Example: Predicts call drop rates if 20% more users join at 8 PM.
- Output: Helps NTC allocate towers dynamically.
- System Dynamics: Simulates network congestion during festivals (e.g., Dashain).
Banks (e.g., NMB, Global IME)
- Monte Carlo Simulation: Assesses loan default risks.
- Example: Simulate 5000 borrowers with varying incomes/interest rates to estimate 90% LTV (Loan-to-Value) risk.
- Output: Adjusts interest rates to minimize defaults.
- Monte Carlo Simulation: Assesses loan default risks.
Nepal Electricity Authority (NEA)
- Discrete-Event + System Dynamics: Models power outages during monsoons.
- Example: Simulates transformer failures (Poisson, λ=0.5/month) and repair times (Exponential, μ=2).
- Output: Identifies critical substations to upgrade.
- Discrete-Event + System Dynamics: Models power outages during monsoons.
Retail (Daraz, Mega Mart)
- Inventory Simulation: Uses system dynamics to avoid stockouts.
- Example: Simulates demand spikes for Diwali gifts (Normal(5000, 1000) units) to set reorder points.
- Inventory Simulation: Uses system dynamics to avoid stockouts.
Worked Example: Simulating a Bank ATM Queue
Scenario: A bank in Thapathali wants to reduce customer wait times. Simulate the queue using discrete-event logic.
Step 1: Define Events and Distributions
| Event | Distribution | Parameters |
|---|---|---|
| Customer arrival | Poisson | λ = 30/hour |
| Service time | Exponential | μ = 20/hour |
| ATM breakdown | Uniform | 0–1 breakdown/hour |
Step 2: Simulate 1 Hour
Assume the ATM starts empty at t=0.
| Time (min) | Event | State Update | Notes |
|---|---|---|---|
| 0 | Start | Queue = 0, Serving = 0 | |
| 2 | Customer arrives | Queue = 1 | Arrival time: Exp(λ=30) |
| 3 | Customer starts service | Serving = 1, Queue = 0 | Service time: Exp(μ=20) |
| 5 | Customer departs | Serving = 0 | |
| 6 | Customer arrives | Queue = 1 | |
| 7 | Customer starts service | Serving = 1, Queue = 0 | |
| 10 | ATM breaks down | Serving = 0, Queue = 1 | Breakdown time: Uniform(0,60) |
| 12 | Customer departs (queue) | Queue = 0 | Waited 5 min |
| 15 | ATM repaired | Serving = 1 (next customer) |
Output Metrics:
- Average wait time: 4.2 minutes.
- Customers served: 6.
- Idle time: 12 minutes (due to breakdown).
flowchart TD
A["t=0\nQueue=0"] --> B["t=2\nArrival\nQueue=1"]
B --> C["t=3\nService starts\nServing=1"]
C --> D["t=5\nDeparture\nServing=0"]
D --> E["t=6\nArrival\nQueue=1"]
E --> F["t=7\nService starts\nServing=1"]
F --> G["t=10\nBreakdown\nServing=0"]
G --> H["t=12\nDeparture\nQueue=0"]
H --> I["t=15\nRepaired\nServing=1"]Recommendation:
- Add a second ATM to reduce wait times by 50%.
- Schedule maintenance during off-peak hours (e.g., 11 PM).
Simulation vs. Analytical Models: Comparison
Not all problems require simulation. Use this table to decide when to simulate:
| Feature | Simulation Models | Analytical Models |
|---|---|---|
| Complexity | High (e.g., traffic, supply chains) | Low (e.g., linear equations) |
| Randomness | Handles uncertainty (probability) | Assumes deterministic inputs |
| Output | Probabilistic (distributions) | Exact (single value) |
| Example Use | Pathao driver routing | Calculating loan EMI |
| Tools | AnyLogic, SimPy, Excel | Math, Solver, Python (SciPy) |
| Time to Build | Weeks (for complex systems) | Minutes (for simple cases) |
When to Use Simulation:
- The system has randomness (e.g., customer arrivals).
- Feedback loops exist (e.g., inventory → demand → restock).
- Exact solutions are impossible (e.g., traffic jams).
When to Avoid Simulation:
- The problem is linear and deterministic (e.g., profit = revenue – cost).
- You need real-time decisions (simulations are slow).
Building a Simulation: Step-by-Step
Follow these steps to build your own simulation (e.g., for a Khalti payment queue):
Define the System:
- Example: Customers arrive to pay bills at a Khalti kiosk.
- State Variables: Queue length, number of tellers.
Identify Events:
- Customer arrival (Poisson, λ=20/hour).
- Payment processing (Exponential, μ=15/hour).
- Teller break (Uniform, 0–30 minutes).
Choose a Tool:
- Excel: For simple DES (use
RAND()for randomness). - Python (SimPy): For complex systems.
- AnyLogic: For visual system dynamics.
- Excel: For simple DES (use
Run the Simulation:
- Generate 1000 runs with different λ/μ.
- Calculate metrics: average wait time, teller utilization.
Validate:
- Compare outputs to real data (e.g., Khalti’s peak hours).
- Adjust distributions if mismatched.
Common Probability Distributions in Simulation
Simulations rely on probability distributions to model randomness. Here are the most used ones:
| Distribution | Use Case | Parameters | Example |
|---|---|---|---|
| Poisson | Event arrivals (e.g., calls, orders) | λ (rate) | Customers arriving at Daraz: λ=50/hour |
| Exponential | Time between events | μ (rate) | Call duration: μ=10/min |
| Normal | Continuous data (e.g., heights, prices) | μ, σ | NEPSE daily returns: μ=0.1%, σ=2% |
| Uniform | Fixed range (e.g., delays) | min, max | ATM repair time: 0–60 min |
| Binomial | Success/failure (e.g., defects) | n, p | Pathao driver acceptance: p=0.7 |
Example: Modeling NTC’s call drop rate.
- Assume drops follow a Poisson process with λ=0.5/hour.
- Probability of no drops in 1 hour: (60.65%).
Pitfalls and How to Avoid Them
Ignoring Randomness:
- Problem: Using fixed values instead of distributions.
- Fix: Always model uncertainty (e.g., demand as Normal, not a constant).
Overfitting:
- Problem: Tuning the model to past data only (e.g., using exact historical λ for customer arrivals).
- Fix: Validate with out-of-sample data.
Long Run Times:
- Problem: Simulating years of data in Excel.
- Fix: Use Python or specialized tools (e.g., SimPy).
Misinterpreting Outputs:
- Problem: Assuming simulation results are exact.
- Fix: Report confidence intervals (e.g., "95% of runs show wait times < 5 min").
Tools for Simulation
| Tool | Type | Best For | Example Use Case |
|---|---|---|---|
| Excel | Discrete-event | Quick prototypes | ATM queue simulation |
| Python (SimPy) | General-purpose | Complex systems | Supply chain optimization |
| AnyLogic | System dynamics | Visual models with feedback loops | Traffic simulation |
| R (simmer) | Discrete-event | Statistical analysis | Healthcare patient flows |
| Arena | Industrial | Manufacturing/logistics | Factory machine scheduling |
Example Code (Python SimPy):
import simpy
def customer(env, name, processing_time):
print(f"{name} arrives at {env.now}")
with bank.teller:
print(f"{name} starts service at {env.now}")
yield env.timeout(processing_time)
print(f"{name} departs at {env.now}")
env = simpy.Environment()
bank = simpy.Resource(env, capacity=1) # 1 teller
for i in range(5):
env.process(customer(env, f"Customer {i}", 2)) # 2-minute service
env.run(until=10)
Output:
Customer 0 arrives at 0.0
Customer 0 starts service at 0.0
Customer 1 arrives at 0.0
Customer 1 starts service at 2.0
...
## Exam Tip
What to Expect in PU Exams:
Theory Questions (30%):
- Define discrete-event simulation vs. Monte Carlo.
- Explain feedback loops in system dynamics (use a diagram).
- Compare simulation to analytical models (table format).
Worked Examples (40%):
- Given: A scenario (e.g., "A hospital has 3 doctors serving patients arriving at λ=10/hour").
- Do:
- Identify distributions (e.g., Poisson arrivals, Exponential service).
- Simulate 1 hour manually (show a table).
- Calculate metrics (e.g., average wait time).
- Common Mistake: Forgetting to account for randomness (e.g., using fixed service times).
Tool-Based Questions (20%):
- Describe how you’d build a simulation in Excel or Python for a given problem.
- Example: "Simulate a Khalti payment queue with 2 tellers."
Short Answer (10%):
- "What is the purpose of warm-up period in simulation?" Answer: Eliminates initial bias from starting conditions (e.g., empty queue).
- "Name two feedback loops in a supply chain." Answer: Order → Inventory (balancing); Demand growth → Production (reinforcing).
High-Scoring Strategies:
- Always draw a diagram for system dynamics or DES (even if not asked).
- Use real-world examples in answers (e.g., "Like Pathao’s driver matching...").
- Show calculations step-by-step for worked examples (e.g., Poisson probability).
- Compare methods in essays (e.g., "Simulation is better than analytical for X because...").
Sample Exam Question and Answer:
Question: "A supermarket in Lakshmi Development has 2 checkout counters. Customers arrive at a rate of 15/hour (Poisson), and each checkout takes 4 minutes (Exponential). Simulate the system for 1 hour and calculate:
- Average queue length.
- Probability a customer waits > 2 minutes."
Answer:
Simulation Steps:
- Use SimPy or Excel to model arrivals/departures.
- Excel Approach:
- Column A: Time (0, 0.05, 0.10, ..., 1 hour).
- Column B: Arrivals (generate Poisson(15) events).
- Column C: Service starts (if counter free).
- Column D: Queue length (track customers waiting).
Time (min) Event Queue Notes 0 Start 0 Counters: Free, Free 2 Arrival (C1) 1 C1 starts service (4 min) 3 Arrival (C2) 2 C2 starts service (4 min) 6 C1 departs 1 7 Arrival (C3) 2 C1 takes C3, C2 takes C2 ... ... ... Run until t=60 Average Queue Length: Sum(queue) / 60 = 1.2 customers.
Probability Wait > 2 Minutes:
- Use M/M/2 queueing theory (approximation):
- (utilization).
- (22.3%).
- Use M/M/2 queueing theory (approximation):
Visual:
Final Checklist Before the Exam:
- Can you draw a discrete-event timeline for a given scenario?
- Do you know 3 real-world Nepalese examples of simulations?
- Can you write a 3-step simulation plan for any problem?
- Do you remember the 4 key distributions (Poisson, Exponential, Normal, Uniform) and their uses?
Based on the PU BBA (PU) syllabus for Data Analysis and Modeling, unit 10.
Discussion
Loading…