r/SimPy • • Jun 28 '25

Pleased to share the "SimPy Simulation Playground"

Post image
19 Upvotes

Just put the finishing touches to the first version of this web page where you can run SimPy examples from different industries, including parameterising the sim, editing the code if you wish, running and viewing the results.

Runs entirely in your browser.

Here's the link: https://www.schoolofsimulation.com/simpy_simulations

My goal with this is to help provide education and information around how discrete-event simulation with SimPy can be applied to different industry contexts.

If you have any suggestions for other examples to add, I'd be happy to consider expanding the list!

Feedback, as ever, is most welcome!


r/SimPy • • Jul 21 '25

You can use Claude Code (and potentially Gemini CLI) to specify, run and analyse your existing simulations in Python entirely agentically

9 Upvotes

Here’s an on-the-fly example of how with Claude Code and a Python simulation in SimPy. In essence, you just need to:

  1. Separate the concerns in the code:

That is, at a minimum, have:

Input parameters --> simulation code --> output data

The more you can separate concerns the better. E.g. this is a step improvement:

Input parameters --> data validation --> simulation code --> output data

2. Then, just let the AI know how to work with your simulation. This is where Claude Code or Gemini CLI really shine - as you specify a CLAUDE.md or GEMINI.md file with all the context instructions.

I’ve also found this useful for debugging complex simulations when there are lots of input and output parameters.


r/SimPy • • Dec 07 '24

Why is this field seemingly so obscure?

9 Upvotes

I've recently learned about DES and have been trying to get into it by looking for resources online (while Harry cooks). But most online sources are hard to find and years old, books are fairly rare and usually expensive. "Simulation engineer" doesn't seem to be an established title like eg. data engineer as far as I can tell.

Is this field truly so niche? DES doesn't strike me as rocket science, so I can't imagine the barrier of entry is higher than say SQL. And I know it's been around for decades.

What gives? this stuff is extremely cool!


r/SimPy • • Dec 03 '25

Simple FE for simpy

8 Upvotes

Hey guys - we built a simple vizualization tool for SimPy simulations. It will help you with client presentations and debugging.


r/SimPy • • Aug 08 '25

Claude Opus 4.1 Makes Great SimPy Simulations

8 Upvotes

Just tested it on my standard prompt which is a conceptual model design of a green hydrogen production system. This was one shot using Claude Code.

Outperformed all other models in my view for its comprehensiveness.

I have documented the results here in the spreadsheet: https://docs.google.com/spreadsheets/d/1vIA0CgOFiLBhl8W1iLWFirfkMJKvnTrN9Md_PkXBzIk/edit?gid=719069000#gid=719069000

Direct link to the colab notebook here: https://colab.research.google.com/drive/1xIn6kPXfDCmlMBr1cNXT8u3zWP4hZBBw#scrollTo=ZaXorKS3NePE

Here's the visualisation which was generated:

By comparison here is what Opus 4 created with the same prompt:

And Gemini 2.5 Pro (albeit Gemini still got the same answer with approx 1/3 the amount of code - it is muuuch more concise and doesn't try to overdeliver):


r/SimPy • • Jun 27 '25

Virtual Simulation Engineer v2

8 Upvotes

This one now uses SimPy under the hood.

Design, build and execute a discrete-event simulation in Python entirely using natural language in a single browser window.

Here's the link to try it out: https://gemini.google.com/share/ad9d3a205479

Let me know what you think!


r/SimPy • • Mar 25 '25

Calling All Industry Users of SimPy - Let’s Share Your Story

7 Upvotes

One big advantage commercial simulation packages like AnyLogic or MATLAB SimEvents have over SimPy is visibility. Companies actively collect and promote glowing case studies from their paying customers. Spend any time on their blogs and you’ll see a constant stream of industry use cases and success stories.

But here’s the thing – I know from personal experience that SimPy is just as widely used in industry (if not more so). The only difference is we don't shout about it enough.

I'm going to change that.

If you use SimPy in an industrial context and would be open to producing a case study together, I’d love to hear from you. I’ll do the heavy lifting on the write-up – all you need to do is share your experience. I’ll then promote it through my network to give your work the visibility it deserves.

Drop me a message if you’re interested – let’s give SimPy the recognition it deserves.

Cheers,

Harry


r/SimPy • • Feb 04 '26

I've always thought Pygame was an excellent library for visualising SimPy simulations - this shows some of the nice visuals that can be achieved

6 Upvotes

r/SimPy • • Feb 04 '26

The “Event Log First” pattern in SimPy (debuggability, KPIs, and replay in one go)

6 Upvotes

I’ve noticed a lot of SimPy models hit the same wall:

  • “It runs… I think?”

  • “How do I compute KPIs without threading variables through every process?”

  • “How do I explain what happened in a run, step-by-step, like a proper record?”

My default answer now is: log events first, analyse later.

Instead of baking metrics into every corner of the model, treat the simulation like a small universe that emits a stream of facts:

  • entity arrived

  • queued

  • started service

  • finished service

  • resource seized/released

  • step started/ended

Then you can derive:

  • waiting times, cycle times, utilisation

  • bottlenecks

  • per-entity narratives (“batch record” style)

  • even a replay/animation later if you feel fancy

Here’s a tiny pattern I’ve been using.

from dataclasses import dataclass, asdict
import simpy

(frozen=True)
class Event:
    t: float
    entity: str
    kind: str
    meta: dict

class EventLog:
    def __init__(self):
        self.events: list[Event] = []

    def add(self, t, entity, kind, **meta):
        self.events.append(Event(t=t, entity=entity, kind=kind, meta=meta))

def customer(env, name, server, log):
    log.add(env.now, name, "arrived")

    with server.request() as req:
        log.add(env.now, name, "queue_enter", queue_len=len(server.queue))
        yield req
        log.add(env.now, name, "service_start", queue_len=len(server.queue))

        service_time = 5
        yield env.timeout(service_time)

        log.add(env.now, name, "service_end", service_time=service_time)

def source(env, server, log, interarrival=3):
    i = 0
    while True:
        i += 1
        env.process(customer(env, f"C{i}", server, log))
        yield env.timeout(interarrival)

env = simpy.Environment()
server = simpy.Resource(env, capacity=1)
log = EventLog()

env.process(source(env, server, log))
env.run(until=30)

# Example: build simple KPIs from the event stream
starts = {}
waits = []
for e in log.events:
    if e.kind == "queue_enter":
        starts[(e.entity, "queue")] = e.t
    if e.kind == "service_start":
        t0 = starts.get((e.entity, "queue"))
        if t0 is not None:
            waits.append(e.t - t0)

print("mean_wait", sum(waits) / len(waits) if waits else 0)
print("num_events", len(log.events))

A few notes:

  • This keeps the model logic clean. It just emits facts.

  • The analysis becomes a separate step. Easier to test, easier to change.

  • You can write the events out to CSV/Parquet and do proper post-processing.

  • If you later want “telemetry-style” time series (temperatures, speeds, etc.), you can log periodic samples as events too (same pattern, different kind).

Curious how others do this.

Do you log everything, or do you prefer embedding stats directly in processes? Any favourite patterns for keeping logs lightweight on big runs?

Also, yes, I am aware this is just “observability” for tiny universes. I’m choosing to be proud of that. :)


r/SimPy • • May 12 '25

I expect this will be of interest to some!

Thumbnail
reddit.com
6 Upvotes

r/SimPy • • Apr 17 '25

Simulate machine limping while waiting for a technician

6 Upvotes

Hello,

I want to simulate a machine that breaks, but it can continue running at a slower rate while it waits for a technician to be available. Once the technician is available then it repairs the machine and the machine continues running at its regular rate.

I have my technicians defined as a

techs = simpy.PreemptiveResource(self.env, capacity=tech_crews)

In my current code, if the tool breaks I request a tech with

with techs.request() as req:
    yield req
yield self.env.timeout(repair_time)

and the machine stops until the tech is available and the machine has been fixed.

What I would like to do is something as follows

techs.request()
machine_rate = machine_rate / 2
# machine continues running
# tech is available
# tech repair
machine_rate = machine_rate * 2

Any pointers or ideas on how to achieve this?

Thank you


r/SimPy • • Feb 26 '25

Mesa vs SimPy

6 Upvotes

Hey all,

I am new to SimPy. I am exploring different libraries for creating simulations in Python, and I am leaning towards using either SimPy or Mesa. I was wondering if anyone had any recommendations for where one shines relative to the other, or if you could point me towards any reading/comparisons that might give me more information.

Currently, I am leaning slightly towards SimPy, but I have only scratched the surface of what either library has to offer.


r/SimPy • • Jan 24 '25

What are you working on at the moment?

6 Upvotes

For me I’m currently building a little case study on simulating a new supply chain.

Aiming to balance total cost of ownership against system performance (e.g. % of deliveries made on time).


r/SimPy • • Oct 05 '26

[Release] Dynamic DES v0.16.0: YAML blueprints as a third way to write a SimPy model, and rebuilt docs

5 Upvotes

Hey r/SimPy,

Following up on v0.11.1 (the declarative API and the Postgres and Redis connectors), Dynamic DES has reached v0.16.0. This release adds a third way to write a simulation, a plain YAML file run with a new ddes command, and rebuilds the documentation around the three ways.

Three ways, one model. The imperative low-level API wires the environment, registry, connectors and SimPy processes by hand. The declarative SimulationContext builder from v0.11.1 describes the model in one block, with decorators handling queueing, resource request and release, and duration sampling. A YAML blueprint now describes the same model with no Python at all. All three build the same parameters and run on the same environment.

Here is the local example: one lathe with capacity 2, parts arriving about once a second, normally distributed milling times, and the lathe's utilisation and queue length sampled every 2 simulation seconds.

simulation:
  sim_id: Factory_A
  factor: 1.0

egress:
  - type: Console

resources:
  lathe: {current_cap: 2, max_cap: 5}

services:
  milling: {dist: normal, mean: 3.0, std: 0.5}

arrivals:
  standard: {dist: exponential, rate: 1.0, spawn: process_part}

tasks:
  process_part:
    service: milling
    resource: lathe
    payload: {event_type: part_produced, quality: A}
    id_field: part_id

telemetry:
  - interval: 2.0
    publish:
      utilization: lathe.utilization
      queue_length: lathe.queue_length

run:
  until: 60

To run it:

curl -O https://raw.githubusercontent.com/jaehyeon-kim/dynamic-des/main/examples/yaml/local.yaml
uv run --no-project --with dynamic-des ddes run local.yaml

What a blueprint can express. Each task emits queued, started and finished events, with no request, timeout or release code, and factor: 0 runs the same model as fast as the machine allows.

How to extend it.

  • ${VAR:-default} reads hosts and credentials from environment variables, with a default when a variable is not set. The same file then runs on your machine and in a test pipeline, with no edits.

  • Logic YAML cannot express, such as an order with a random number of line items, goes in a Python function referenced with !python.

Docs rebuilt. The tutorials now build the same factory three times, once in each way, and each example page shows its versions side by side in tabs.

Links


r/SimPy • • Jul 17 '26

[Release] Dynamic DES v0.11.1 - a declarative API, plus Postgres and Redis connectors

Post image
5 Upvotes

Hey r/SimPy,

Following up on the v0.8.1 release (dual-mode batch and streaming execution), Dynamic DES has reached v0.11.1. This update is less about data pipelines and more about how you write a simulation and where it can connect.

A new declarative API. Earlier versions were purely imperative, wiring up the environment, registry, connectors, and processes by hand. The default is now a SimulationContext builder that describes a whole model in one block, with decorators handling the usual SimPy boilerplate (queuing, resource request and release, duration sampling, telemetry):

from dynamic_des import SimulationContext, ConsoleEgress

app = (
    SimulationContext(sim_id="Line_A", factor=1.0, random_seed=42)
    .add_resource("lathe", current_cap=1, max_cap=5)
    .add_arrival("standard", dist="exponential", rate=1.0)
    .add_service("milling", dist="normal", mean=3.0, std=0.5)
    .add_egress(ConsoleEgress())
)

@app.arrival_loop("standard")
def arrivals(ctx):
    i = 0
    while True:
        yield ctx.wait_for_arrival("standard")
        ctx.spawn(work_task(i)); i += 1

@app.task(service_id="milling", resource_id="lathe")
def work_task(task_id):
    return {"part_id": task_id}

app.run(until=25.0)

The imperative low-level API is still fully supported for advanced control flows.

New Postgres and Redis connectors. Because I/O is decoupled from simulation logic through a central registry, adding a backend is mostly a connector. This release adds matching ingress and egress for Redis (low-latency, in-memory push and pull for live dashboards and control) and PostgreSQL (stream events and telemetry into a table, or drive parameters from one). They sit alongside the existing Kafka path and Parquet/JSONL historical export, so one model can ingest from and emit to Kafka, Redis, or Postgres without touching its core logic. A v0.11.1 patch also fixes threading races during environment teardown.

Links


r/SimPy • • May 23 '26

SimPy Essentials - a New Course on Udemy

5 Upvotes

Hi folks,

Apologies for the shameless plug - but there's little in the way of learning resources out there on SimPy, so I felt it was worth sharing that I just launched a course on Udemy covering the fundamentals of SimPy.

It's called SimPy Essentials 2026

The course covers all of the key aspects of the library, as well as giving an introduction to different simulation approaches. Comes with lots of downloadable code examples in Jupyter Notebooks and everything is grounded in real world industry examples so my aim is to make the course as practical and industry relevant as possible. It also comes with my book on SimPy thrown in for free.

If you would like to enrol enter the coupon code HAPPY-SIMULATING for a discount - note that the coupon expires in 5 days.

Hope you find it helpful if you do take the course and feel free to ask me any questions here.


r/SimPy • • Jun 30 '25

[Tool] Discover Ciw — A Powerful Python Library for Queueing Network Simulation 🚦🐍

5 Upvotes

Hi r/SimPy! 👋

If you enjoy working with discrete event simulation in Python, you might want to check out Ciw — a library focused on simulating open queueing networks with rich features.

✨ What makes Ciw stand out?

  • Multi-class customer flows with dynamic routing 🔄

  • Realistic behaviors like blocking 🚫, baulking 🤚, and reneging 🏃‍♂️

  • Scheduling ⏰, batch arrivals 📦, slotted services ⏳, and priority disciplines ⚡

  • Deadlock detection ⚠️ — crucial for complex network modeling!

While SimPy offers great flexibility as a general discrete event simulation framework, Ciw provides a specialized, ready-to-use environment for queueing networks, ideal for modeling service systems, healthcare, call centers, and more.

We’ve also built a friendly community at r/CiwPython for sharing models, asking questions, and collaborating on simulation projects.

If you’re curious about expanding your Python simulation toolkit or want to compare approaches, come join the conversation! 🚀


r/SimPy • • Feb 10 '25

How to structure complex simulations?

5 Upvotes

So I'm building a simulation where jobs are handed to a factory and the factory has multiple assembly lines and each assembly line has a bunch of robots which each do a number of tasks etc. I'm wondering how to scale this so I can manage the complexity well, but stay flexible. Has anyone done anything big like that? The examples on the website seem useful but not quite on point.

For example I have a lot of stuff that looks like this:

import simpy

# Dummy function that simulates work
def buy_it(env):
    print(f'{env.now}: buy it started')
    yield env.timeout(2)
    print(f'{env.now}: buy it finished')

def use_it(env):
    print(f'{env.now}: use it started')
    yield env.timeout(3)
    print(f'{env.now}: use it finished')

def break_it(env):
    print(f'{env.now}: break it started')
    yield env.timeout(1)
    print(f'{env.now}: break it finished')

def fix_it(env):
    print(f'{env.now}: fix it started')
    yield env.timeout(2)
    print(f'{env.now}: fix it finished')

# More complex task
def technologic(env):
    # Describe all the steps of this particular task
    yield from buy_it(env)
    yield from use_it(env)
    yield from break_it(env)
    yield from fix_it(env)

# Setting up the SimPy environment and running the process
env = simpy.Environment()
env.process(technologic(env))
env.run()

Is the yield from recommended? Should I make processes of each sub step? What if I want to build another layer around this to run two workers which can each run one technologic task and work a job queue? Can I just keep adding more layers?

Another problem is scale. I think I should probably not schedule a million jobs and let them all wait on a resource with a capacity of 2. But writing a generator which makes a million jobs is probably trivial. How do I get a constant trickle that generates more jobs as soon as the system is ready to handle them? I want to simulate the case that there is always more work.

I'm curious to see what others make of this. Hope it's not to abstract, but I can't share my real code for obvious reasons.


r/SimPy • • Feb 08 '25

Simulation for Financial Scenarios

5 Upvotes

Currently working on integrating a financial model with operations model to determine risk. Anyone out there who has worked with financial metrics and been successful? Thanks 😎


r/SimPy • • Dec 27 '24

Found a nice little free tutorial on SimPy in a Google Colab notebook

Thumbnail
colab.research.google.com
5 Upvotes

r/SimPy • • Sep 05 '24

Nice SimPy animation - mining use case

Thumbnail
youtube.com
5 Upvotes

r/SimPy • • Apr 19 '26

Major update to dynamic-des: Custom variables and Kafka event routing for sophisticated simulations

Post image
4 Upvotes

Hello r/SimPy!

A while back I shared dynamic-des, a package I built for updating resource capacities on the fly. I wanted to share major updates today showing how much the scope of the package has expanded. I have added two major features to help build and stream sophisticated physical simulations:

1. Mutating Custom Variables on the Fly

In standard DES, modeling hidden machine degradation (like a roller slowly wearing out or suddenly breaking) is tricky if you want external systems to interact with it. To solve this for a Hot Strip Mill simulation I was building, I updated the package to allow custom variables inside the SimPy environment. Using the package's Kafka integration, a user can now use an external web dashboard to inject a control message directly into the running SimPy loop. This instantly mutates a wear_state variable and alters the physics engine's output on the fly for the very next slab of steel.

2. Custom Kafka Topic Router

I also added a custom event router. On top of the standard telemetry and lifecycle events, you can now route specific simulation records to entirely different Kafka topics. This is essential for building modern data pipelines; for example, it allows me to cleanly separate immediate model prediction events and delayed ground-truth physical events into their own dedicated streams right from the simulation.

Full Architecture

I wired all of this up into a complete Event-Driven Architecture where an external Apache Flink pipeline tries to predict the output of the SimPy model using Online Machine Learning.

If you want to see a reference architecture for how dynamic-des handles external state injections and custom event routing to generate realistic, streaming concept drift, check out the repo!


r/SimPy • • Nov 26 '25

Two ways to request resources in SimPy - and why I prefer the "verbose" one

4 Upvotes

If you've worked with SimPy, you've probably seen the with statement pattern everywhere in the docs:

def customer(env, resource):
    with resource.request() as req:
        yield req
        # use the resource
        yield env.timeout(5)
    # resource automatically released here

Clean, right? The context manager handles the release for you. But there's another way that I've come to prefer – explicit requests and releases:

def customer(env, resource):
    req = resource.request()
    yield req
    # use the resource
    yield env.timeout(5)
    resource.release(req)

"But that's more code!" I hear you say. Yes. And that's partly the point.

Why I favour the explicit approach

1. It forces discipline

When you have to write resource.release(req) yourself, you're forced to think about when that release happens. You can't just let Python handle it when the block ends. This matters because in simulation modelling, the timing of resource releases is often critical to your model's behaviour. Making it explicit keeps you honest.

2. It gives you more flexibility

Sometimes you don't want to release at the end of a neat code block. Maybe you need to:

  • Release early based on a condition

  • Release in a different branch of logic

  • Hold onto a resource across multiple yield statements where the release point isn't obvious

With explicit releases, you put the resource.release(req) exactly where the logic demands it.

3. Multiple resources get messy fast

This is the big one. Say you need a machine AND an operator. With context managers:

def job(env, machine, operator):
    with machine.request() as machine_req:
        yield machine_req
        with operator.request() as operator_req:
            yield operator_req
            # now we have both
            yield env.timeout(10)
        # operator released
    # machine released

That nesting gets ugly. And what if you don't release them at the same time? What if the operator can leave after setup but the machine stays occupied? Now you're fighting the structure.

Compare with explicit:

Flat, readable, and the resource lifecycle is right there in the code.def job(env, machine, operator):
    machine_req = machine.request()
    yield machine_req
    
    operator_req = operator.request()
    yield operator_req
    
    # setup phase - need both
    yield env.timeout(2)
    
    # operator can leave, machine keeps running
    operator.release(operator_req)
    
    yield env.timeout(8)
    
    machine.release(machine_req)

The counterargument

The with statement exists to prevent you forgetting to release. Fair point. But if you're building simulations of any complexity, you should be testing them anyway – and a forgotten release shows up pretty quickly when your queues grow forever.

I'd rather have code where I can see exactly what's happening than code that hides important behaviour behind syntactic sugar.

Anyone else have a preference? Interested to hear if others have run into the nested with problem.


r/SimPy • • May 31 '25

Car Service Simulation - SimPy Tutorial (looking for feedback)

Thumbnail
teachyourselfsystems.com
4 Upvotes

I want t put together a somewhat dense simulation script together that can act as a good tutorial for a software developer that knows Python and recently discovered SimPy. This is the best I could come up with so far. Any ideas for improvements? Thanks!


r/SimPy • • Mar 08 '25

How to integrate simpy with maps?

4 Upvotes

I have a project requiring me to integrate multilayered world maps (openstreetmap or google maps) with a python script. I would like to show entities (trucks, trains) are flowing through those maps and be displayed. However, as far as I understand SimPy is a resource based discrete event simulation library and not an entity based one.

So my question is, do I need to define some shadow entities within simpy’s environment to make this possible or are there any built in methods exist?