Simpy

Automate and integrate SimPy for discrete-event simulation and process modeling workflows

SimPy is a community skill for discrete-event simulation using the SimPy Python library, covering process modeling, resource management, event scheduling, monitoring, and statistical analysis for system performance evaluation.

What Is This?

Overview

SimPy provides tools for building discrete-event simulations that model real-world processes in Python. It covers process modeling that defines entities moving through system stages with time delays and decision logic, resource management that simulates shared resources with capacity limits and queuing behavior, event scheduling that coordinates process timing and inter-process communication, monitoring that collects statistics during simulation execution, and statistical analysis that evaluates system performance metrics from simulation results. The skill helps engineers model and optimize complex systems before committing to costly physical changes or infrastructure investments.

Who Should Use This

This skill serves operations researchers modeling system throughput, engineers evaluating process designs before implementation, and analysts studying queuing behavior and resource utilization. It is also well suited for supply chain planners and capacity planners who need to test scenarios under variable demand conditions.

Why Use It?

Problems It Solves

Real-world system experiments are expensive and time-consuming to conduct. Analytical formulas cannot capture complex interactions between system components. Spreadsheet models lack the ability to represent dynamic time-dependent processes. Performance predictions without simulation miss bottlenecks that emerge under load.

Core Highlights

Process builder defines entities with time delays and decision logic. Resource manager simulates shared capacity with queuing. Event scheduler coordinates timing and process communication. Statistics collector tracks performance metrics during execution.

How to Use It?

Basic Usage

import simpy
import random

def customer(
  env, name,
  counter, stats
):
  arrive = env.now
  with counter.request()\
    as req:
    yield req
    wait = env.now - arrive
    stats['waits'].append(
      wait)
    service = random\
      .expovariate(1.0 / 5)
    yield env.timeout(
      service)
    stats['served'] += 1

def arrivals(
  env, counter, stats
):
  i = 0
  while True:
    yield env.timeout(
      random.expovariate(
        1.0 / 3))
    i += 1
    env.process(
      customer(
        env,
        f'C{i}',
        counter,
        stats))

stats = {
  'waits': [],
  'served': 0}
env = simpy.Environment()
counter = simpy.Resource(
  env, capacity=2)
env.process(
  arrivals(
    env, counter, stats))
env.run(until=100)
avg_wait = (
  sum(stats['waits']) /
  max(len(
    stats['waits']), 1))
print(
  f'Served: '
  f'{stats["served"]}')
print(
  f'Avg wait: '
  f'{avg_wait:.1f}')

Real-World Examples

import simpy
import random

class Factory:
  def __init__(
    self, env,
    machines: int,
    inspectors: int
  ):
    self.env = env
    self.machine = (
      simpy.Resource(
        env, machines))
    self.inspector = (
      simpy.Resource(
        env, inspectors))
    self.produced = 0
    self.defects = 0

  def manufacture(
    self, item: str
  ):
    with self.machine\
      .request() as req:
      yield req
      yield self.env\
        .timeout(
          random.uniform(
            3, 7))
    with self.inspector\
      .request() as req:
      yield req
      yield self.env\
        .timeout(
          random.uniform(
            1, 2))
      if random.random()\
        < 0.05:
        self.defects += 1
      else:
        self.produced += 1

def run_factory(
  env, factory
):
  i = 0
  while True:
    yield env.timeout(
      random.uniform(1, 3))
    i += 1
    env.process(
      factory.manufacture(
        f'Item-{i}'))

env = simpy.Environment()
factory = Factory(
  env, machines=3,
  inspectors=1)
env.process(
  run_factory(
    env, factory))
env.run(until=480)
print(
  f'Produced: '
  f'{factory.produced}')
print(
  f'Defects: '
  f'{factory.defects}')

Advanced Tips

Use SimPy containers for modeling continuous resources like fuel tanks or inventory levels. Run multiple replications with different random seeds to compute confidence intervals for results. Combine SimPy with matplotlib to visualize resource utilization over time. When debugging complex models, use SimPy's event tracing to log process state transitions and identify unexpected timing interactions between concurrent processes.

When to Use It?

Use Cases

Model a customer service center to determine the optimal number of agents for target wait times. Simulate a manufacturing line to identify bottleneck stations that limit throughput. Evaluate network packet processing under varying traffic loads. Simulation is particularly valuable when comparing multiple design alternatives, since each scenario can be tested rapidly without physical prototyping.

Related Topics

Discrete-event simulation, queuing theory, operations research, SimPy, process modeling, resource management, and Monte Carlo.

Important Notes

Requirements

SimPy Python package installed via pip. Understanding of the system being modeled including process flows and resource capacities. Statistical knowledge for interpreting simulation results.

Usage Recommendations

Do: validate simulation models against known system behavior before using them for predictions. Run simulations long enough for steady-state results to avoid transient bias. Use multiple random seeds to assess result variability.

Don't: treat single simulation runs as definitive since results vary with random number sequences. Model every minor detail since overly complex models are slow and hard to validate. Assume simulation results transfer directly to real systems without validation.

Limitations

Simulation accuracy depends on how well the model represents actual system behavior and timing distributions. Discrete-event simulation cannot model continuous physical processes without approximation. Complex models with many interacting resources may require long execution times for reliable results.