r/SimPy • • Mar 07 '25

Simulations for Computer Systems?

4 Upvotes

I have a need to do some analysis on computer system which includes CPUs, caches, memories, other processing elements (streaming type), interconnections (AXI, Ethernet, DMA, etc.), etc. Would SimPy be suitable for such computer systems when there is no actual application software available yet and the need is to verify the system architecture feasibility in the defined cases? Or are there better solutions or approaches?

What about other frameworks like Salabim (https://www.salabim.org/) or PyDES (https://pydes.readthedocs.io/en/latest/), how to these compare to SimPy and what would be the easiest to start with?


r/SimPy • • Nov 04 '24

A quick vlog: the real challenge in simulation isn’t the code - it’s winning people over

Thumbnail
linkedin.com
4 Upvotes

r/SimPy • • Sep 11 '24

Decent introductory lecture on SimPy from PyData NYC 2022

Thumbnail
youtube.com
4 Upvotes

r/SimPy • • Apr 29 '26

Simulation Bench: an attempt at evaluating how well LLMs, agent harnesses, agent skills and frameworks contribute to good modelling and simulation work - specifically with SimPy as the underlying simulation engine

3 Upvotes

There are many models, many agent harnesses, many skills and many workflows out there. For a modelling and simulation engineer this is difficult territory to navigate through.

I have been testing many combinations myself, generally being guided by my intuition, but always with a question mark about what really is best.

So I decided to try and solve this problem by building my own benchmark, specifically aimed at modelling and simulation people, and even more specifically for those who like to work in Python.

The benchmark I have created covers almost the entire modelling simulation lifecycle. From studying the problem, building a conceptual model through to writing code and outputting results. I have quantitative scoring, qualitative scoring and a consistent methodology for evaluation.

The challenge I pose is evaluating the throughout for a range of scenarios on a mine site. The input data contains node and edges data for the paths in this site and scenarios are provided which need investigation. This is just the first idea I had that came to mind, other simulation challenges can be introduced later.

It captures the kind of relevant detail I wanted to capture:

  1. Which model

  2. Which harness

  3. Which workflow or skills (if any)

It's not perfect, but it serves a purpose right now, and the results are making sense based on my own subjective experience.

At the time of writing this post I can report:

  1. Claude Opus 4.7 leads the pack in "Max" mode. Running with the Superpowers skill gives a slight edge at a cost of doubling token count and tripling time to completion.

  2. GPT 5.5 - if you have followed my previous benchmnarking you will know that I was NOT a fan of the OpenAI models for SimPy. However GPT 5.5 has done an OK job here. That said, it was on par with Sonnet 4.6 overall.

  3. Gemini 3.1 Pro consistently underperformed and there was a massive variation depending on which harness and skill being used. OpenCode (set to "high") marginally outperformed Gemini CLI, but absolutely tanked itself when used with the Superpowers skill (the opposite behaviour to Claude Code).

  4. The Pi agent - the minimal coding agent harness - in total vanilla mode significantly underperformed. This is not a criticism of Pi, since it is an agent harness which is meant to be extended. It simply goes to show how important a harness is for AI performance and you should be conscious of this.

  5. GSD2 barely outperformed vanilla Pi. I did not track the token count for this one, but I do not recommend right now.

  6. Correlation analysis showed a small correlation of 0.25 between token spend and overall score. However, interestingly, more token spend was slightly negatively correlated with interpretability and the conceptual model design.

Here's the link to the benchmark: https://simulation-bench.fly.dev/


r/SimPy • • Mar 23 '26

[Release] dynamic-des v0.1.1 - Mutate SimPy parameters at runtime and stream outputs

3 Upvotes

Hello r/SimPy,

I recently released dynamic-des (v0.1.1). It acts as a real-time control plane for SimPy, allowing you to mutate simulation parameters (like resource capacities) while the environment is running, and stream telemetry asynchronously to external systems like Kafka.

import logging
import numpy as np
from dynamic_des import (
    CapacityConfig, ConsoleEgress, DistributionConfig,
    DynamicRealtimeEnvironment, DynamicResource, LocalIngress, SimParameter
)

logging.basicConfig(
    level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s"
)
logger = logging.getLogger("local_example")

# 1. Define initial system state
params = SimParameter(
    sim_id="Line_A",
    arrival={"standard": DistributionConfig(dist="exponential", rate=1)},
    resources={"lathe": CapacityConfig(current_cap=1, max_cap=5)},
)

# 2. Setup Environment with Local Connectors
# Schedule capacity to jump from 1 to 3 at t=5s
ingress = LocalIngress([(5.0, "Line_A.resources.lathe.current_cap", 3)])
egress = ConsoleEgress()

env = DynamicRealtimeEnvironment(factor=1.0)
env.registry.register_sim_parameter(params)
env.setup_ingress([ingress])
env.setup_egress([egress])

# 3. Create Resource
res = DynamicResource(env, "Line_A", "lathe")

def telemetry_monitor(env: DynamicRealtimeEnvironment, res: DynamicResource):
    """Streams system health metrics every 2 seconds."""
    while True:
        env.publish_telemetry("Line_A.resources.lathe.capacity", res.capacity)
        yield env.timeout(2.0)


env.process(telemetry_monitor(env, res))

# 4. Run
print("Simulation started. Watch capacity change at t=5s...")
try:
    env.run(until=10.1)
finally:
    env.teardown()

Why build this?

Unlike standard SimPy, which runs static models synchronously from start to finish, dynamic-des turns your simulation into an interactive, live-streaming environment. I built this to bridge the gap between traditional simulation and modern real-time data architectures, turning end-of-run CSV reports into real-time data streams for Digital Twins.

Key Implementation Details:

  • Async-Sync Bridge: Thread-safe Ingress/Egress MixIns run asyncio background tasks for modern I/O without blocking SimPy's internal clock.

  • Runtime Registry: Safely manages on-the-fly capacity and probability distribution updates.

  • Strict Contracts: All outbound data is validated via Pydantic.

  • Kafka Integration: Embedded producers/consumers turn the script into a first-class Kafka citizen. The repo also includes a live NiceGUI dashboard example.

If you've ever wanted to "remote control" a running SimPy environment, I'd love your feedback!

pip install dynamic-des


r/SimPy • • Nov 11 '25

[Project] Plugboard framework for complex process simulation

3 Upvotes

Hi SimPy users

I've been helping to build plugboard - it's a framework for modelling complex processes, and provides a different approach for modelling compared with SimPy. Whilst it does support events, it has a much stronger emphasis towards discrete-time simulations. Would love to hear from anyone with experience in building these types of models, or has been looking for a framework with support for different modelling paradigms.

What is it for?

We originally started out helping data scientists to build models of industrial processes where there are lots of stateful, interconnected components. Example usage could be a digital twin of a mining process, or a simulation of multiple steps in a factory production line.

Plugboard lets you define each component of the model as a Python class and then takes care of the flow of data between the components as you run your model. It really shines when you have many components and lots of conneections between them (including loops and branches). You can also define and emit events, for example to capture data from the model when specific conditions are encountered. We've also integrated it with Ray to help with running computationally intensive simulations.

Key Features

  • Reusable classes containing the core framework, which you can extend to define your own model logic;

  • Support for different simulation paradigms: discrete time and event based.

  • YAML model specification format for saving model definitions, allowing you to run the same model locally or in cloud infrastructure;

  • A command line interface for executing models;

  • Built to handle the data intensive simulation requirements of industrial process applications;

  • Modern implementation with Python 3.12 and above based around asyncio with complete type annotation coverage;

  • Built-in integrations for loading/saving data from cloud storage and SQL databases;

  • Detailed logging of component inputs, outputs and state for monitoring and process mining or surrogate modelling use-cases.

Links


r/SimPy • • Aug 30 '25

Coroutines, Semi-Coroutines, and the Origins of SimPy

Thumbnail
youtube.com
3 Upvotes

Based on some discussion in

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

I decided to read

gnosis.cx/publish/programming/charming_python_b5.txt.

Some audio issues kick in around 38 minutes in: What happened to my audio quality after 38 minutes? : r/NewTubers which I didn't notice while recording/posting. I don't expect I'll go back to re-record, but now I know I cannot trust that microphone.


r/SimPy • • Aug 07 '25

New manifesto from Klaus Müller (the creator of SimPy) and co-authored by me

Thumbnail reddit.com
3 Upvotes

r/SimPy • • May 03 '25

Tried using Entity-Component-System for a SimPy model and honestly… it’s pretty decent

3 Upvotes

You ever look at your simulation code and think, “This is getting way too complex”?

That was me a few months ago - OOP spaghetti everywhere, random methods buried in class hierarchies, and a creeping sense that I was the problem.

So I decided to try out ECS - that architecture pattern all the game devs use. Turns out, it actually works really well for SimPy simulations too.

Here’s the vibe:

  • Entities: just IDs. They’re like name tags for your stuff (machines, people, whatever).

  • Components: dumb little data containers. Stuff like Position, Status, Capacity. They describe what the entity is.

  • Systems: this is where the actual logic lives. They go, “which entities have X and Y?” and then make them do things. It’s clean and elegant.

You can add new behaviours without blowing up the whole codebase. No need to inherit from 14 classes or refactor everything. Just add a new component and a new system. Done.

It’s basically a form of “extreme composition” so it’s useful for when you need reconfigurability at scale.

Anyway, I’m curious - anyone else using ECS for simulations? Any gotchas to share?


r/SimPy • • Mar 25 '25

Good repos

3 Upvotes

I've been making a pretty big DES model with user inputs to simulate a manafacturing line. Are there any repos people would recommend for best practices for when your project gets so big? Ik things like unit tests are important, what's the best way to implement this stuff.


r/SimPy • • Mar 22 '25

Trouble in Real Time Simulations

3 Upvotes

I am currently working on a real time simulation using simpy and I must say it is a great framework for DES. There is a line introduced there which states: Events scheduled for time t may take just up to t+1 for their computation, before an error is raised. This line is causing me trouble during simulations. What is the purpose of this line? Can one not simply surpass it by increasing the time factor


r/SimPy • • Feb 18 '25

Here's an advert I'm currently running for my SimPy guide - thought some of you might find this interesting

Thumbnail
reddit.com
3 Upvotes

r/SimPy • • Dec 27 '24

A Complete Guide To Using SimPy For AI Simulations & Testing

Thumbnail
medium.com
3 Upvotes

r/SimPy • • Dec 01 '24

How would you implement an arbitrary service discipline with SimPy?

3 Upvotes

I didn't realize that this community existed when I made this comment, so I am migrating it here:

How would you implement an arbitrary service discipline with SimPy? That is, be able to provide a function which selects the next service according to an arbitrary criteria to select among which customer/patient/job/packet gets served at a resource next. This could depend on state or time as well.

https://en.wikipedia.org/wiki/Network_scheduler

I have seen approaches that work by subclassing components of SimPy, but they also violate the public API by using (so-called) protected attributes. I am curious how someone who is only willing to build on top of SimPy without changing SimPy itself would approach this problem.


r/SimPy • • Oct 13 '24

What do you want to see in my new course on simulation in Python with SimPy?

3 Upvotes

Edit: the course is now live - you can find more information here: https://simulation.teachem.digital/school-of-simulation-enterprise

Hi folks, I am gathering some data to help design a new SimPy course I am building.

If you'd like to contribute I'd be really grateful for your feedback here - please select all that apply: https://www.teachem.digital/simulation-course/help-design-the-simulation-course


r/SimPy • • Oct 27 '26

[Release] desflow v0.25.0 (formerly Dynamic DES): reneging and breakdowns in YAML, experiments, and checks against queueing theory

2 Upvotes

Hey r/SimPy,

Following up on v0.16.0 (YAML blueprints), Dynamic DES is now desflow, and has reached v0.25.0. The new name follows a wider scope: whole simulation studies now, and a server to run them next (Why desflow). It still streams its events to Kafka, Redis, PostgreSQL, Parquet and Iceberg.

Renamed in v0.20.0. The package, the module and the command are all desflow now. import dynamic_des and ddes still work with a warning until v0.30.0. The GitHub repository redirects from the old name, and the docs moved to jaehyeon.me/desflow.

Patterns you used to code by hand. Reneging, balking, breakdowns and a task that holds several resources at once are settings since v0.22.0, in YAML and in the builder. Each order that gives up or is turned away is published as an event and counted:

tasks:
  pack:
    service: packing
    resource: packers
    patience: attr.patience    # renege after waiting this long
    balk: t >= 100             # turn new orders away from 100 s

A resource's breakdown block takes a time to failure, a repair time, and whether the work in progress is interrupted. Stores and containers, priority queues, preemption, signals and replay of recorded arrivals are in too.

SimPy parity. You can now write any SimPy 4.1.2 model in YAML, the builder or the low-level API, apart from two differences kept by design. The SimPy Compatibility page lists each feature with the test that checks it against plain SimPy.

Studies from the command line:

  • desflow run --replications 10 gives each statistic's mean and 95% half-width, with a warm-up period left out.

  • desflow experiment compares designs with common random numbers, checks a bound, compares a design with observed values, and writes a report. It exits non-zero when a check fails, so it can run in CI.

  • desflow fit fits measured times to every distribution family and writes the best fit as a setting the model loads.

  • desflow explain (new in v0.25.0) computes λ, μ, c and ρ for each resource without running the model, flags an unstable one, and --verify compares the formulas with replications.

Writing models. A JSON Schema of every setting gives editor completion, and an agent skill teaches an AI coding assistant to write, check and run a model.

To try it on your machine:

pip install desflow
desflow examples get experiment --api yaml
cd experiment/yaml
desflow explain experiment_shop.yaml
desflow experiment experiment.yaml

The example asks whether a third packer keeps the mean wait under 2 seconds, and the last command answers it.

Links


r/SimPy • • Nov 28 '25

Help with bachelor's thesis

2 Upvotes

Hi, guys. I am not a native English speaker so if you will be puzzled by some obscure wording in the post, please, ask away. So I have a theme for my Bachelor's Thesis which is essentially "Automatization of a system of video fixation of traffic violations using discrete event modelling". I didn't contact my thesis supervisor yet (there are some problems with thesis mentorship in general, because my uni is kinda shitty to be honest). So, my question is will SimPy be of any help? I assume it's Python documentation on Discrete Event modellig.


r/SimPy • • Jul 09 '25

Gemini CLI is my preferred AI tool for developing SimPy simulations at the moment

Post image
2 Upvotes

r/SimPy • • May 15 '25

Trying to model a robotic system

2 Upvotes

I am struggling a bit when modeling my system. It is a robotic system with two containers receiving items on a regular time interval. When a user-defined number of items are present in either container, a request is made for a robot to 'pick' these items and place them in a third container. The 'robot' is a resource with capacity =1. The robot has a cycle time of 2 sec. 1 second is used to place the items in container 3, and the remaining second is for returning and thus becoming available again. When the robot places items in container 3, container 3 it is unavailable for 3 seconds. I am using timeout statements to simulate the cycle times. The issue I am struggling with is: I want the robot to timeout for half of it's cycle, then start the timeout for container three and simultaneously begin the timeout for the remaining half of the robot cycle. My current solution has to wait for the container 3 timeout to complete before I can begin the remaining timeout for the robot because I yield the timeouts sequentially. How can I do this?

Here is the problem area.

yield 
env.timeout(robot_cycle/2)
yield 
env.timeout(Container3)
yield 
env.timeout(robot_cycle / 2)

Would appreciate any insight into this.


r/SimPy • • Apr 28 '25

Adding item to the front of a Store queue

2 Upvotes

Is there any way to add an item to the front of store queue?

I know it’s possible to use priorities to change the order, but I was wondering if I can just put an item in a specific location in the queue.

Thanks


r/SimPy • • Apr 18 '25

I Wrote 9 Articles Comparing Various Leading Discrete-Event Simulation Softwares Against Python's SimPy

Thumbnail
reddit.com
2 Upvotes

r/SimPy • • Jan 07 '25

Found a cracking little series of Youtube video tutorials on SimPy which are hot off the press

Thumbnail
youtube.com
2 Upvotes

r/SimPy • • Jan 01 '25

Edge case to be aware of when using AnyOf events

Thumbnail
stackoverflow.com
2 Upvotes

r/SimPy • • Oct 03 '24

How I Helped Build a Production Simulation - and How You Can Too

2 Upvotes

Hey everyone! I recently had an interesting discussion in the SimPy Google Group with someone named Sebastian who was just getting started with the SimPy framework. He had a question that I'm sure resonates with many people trying to simulate complex systems:

"How can I build a simulation model for a production site that uses a weekly production plan as input?"

Sebastian wanted to produce products as efficiently as possible, given the constraints of his model. I thought this was a great use case for SimPy since it's a powerful tool for modelling discrete-event processes. So, I decided to share a modular approach that could help. Here’s a summary of what I advised, including a code example that might help others facing similar challenges.

🏗️ A Modular Production Line Simulation

Sebastian was interested in breaking his production line down into smaller components like buffers, machines, and transport, and optimising the process. This approach is exactly what SimPy excels at! Breaking down complex systems into smaller components makes it easier to manage, helps you identify bottlenecks, and allows for incremental changes.

To help him, I created a simple modular production line simulation in SimPy and showed how to log the key events and visualise the process using Pandas and Seaborn. Let’s break down how we did it:

📊 Here's How We Did It

Below is a Python script demonstrating how to:

  1. Model production processes with SimPy.

  2. Log events in a structured way.

  3. Visualise the production timeline using Seaborn to create a Gantt chart.

The key parts of the simulation are:

  1. Defining Resources: We represent the production line machines as SimPy resources. For example, we define a Heater, Processor, and Cooler, each with a capacity of 1.

  2. Production Processes: The production_process function simulates each product's journey through heating, processing, and cooling. For each step, we request access to the appropriate machine and log the start and end times.

  3. Logging Events: Events are logged in a dictionary (like start time and end time of each step), which we later convert into a Pandas DataFrame. This helps us analyse the results more effectively.

  4. Visualising the Timeline: Using Seaborn and Matplotlib, we create a Gantt chart showing the timeline of each product's production. This makes it easy to identify bottlenecks and inefficiencies.

🖥️ The Code:

import simpy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Initialise the data logging dictionary
log_data = {
    'Product': [],
    'Process': [],
    'Start_Time': [],
    'End_Time': []
}

# Define the production processes
def production_process(env, name, machines, log_data):
    """Simulates the production process of a single product."""
    # Process 1: Heating
    with machines['Heater'].request() as request:
        yield request
        start_time = 
        yield env.timeout(2)  # Heating time
        end_time = 
        log_data['Product'].append(name)
        log_data['Process'].append('Heating')
        log_data['Start_Time'].append(start_time)
        log_data['End_Time'].append(end_time)
   
    # Process 2: Processing
    with machines['Processor'].request() as request:
        yield request
        start_time = 
        yield env.timeout(3)  # Processing time
        end_time = 
        log_data['Product'].append(name)
        log_data['Process'].append('Processing')
        log_data['Start_Time'].append(start_time)
        log_data['End_Time'].append(end_time)
   
    # Process 3: Cooling
    with machines['Cooler'].request() as request:
        yield request
        start_time = 
        yield env.timeout(1)  # Cooling time
        end_time = 
        log_data['Product'].append(name)
        log_data['Process'].append('Cooling')
        log_data['Start_Time'].append(start_time)
        log_data['End_Time'].append(end_time)

def product_generator(env, machines, log_data, weekly_plan):
    """Generates products based on the weekly production plan."""
    for i, product in enumerate(weekly_plan):
        yield env.timeout(product['arrival_time'])
        env.process(production_process(env, f'Product_{i+1}', machines, log_data))

# Set up the simulation environment
env = simpy.Environment()

# Define the machines as resources
machines = {
    'Heater': simpy.Resource(env, capacity=1),
    'Processor': simpy.Resource(env, capacity=1),
    'Cooler': simpy.Resource(env, capacity=1)
}

# Example weekly production plan
weekly_plan = [
    {'arrival_time': 0},
    {'arrival_time': 1},
    {'arrival_time': 2},
    {'arrival_time': 3},
    {'arrival_time': 4},
]

# Start the product generator
env.process(product_generator(env, machines, log_data, weekly_plan))

# Run the simulation
env.run()

# Convert log data into a DataFrame
df = pd.DataFrame(log_data)

# Visualise the production timeline
plt.figure(figsize=(12, 6))
sns.set_style("whitegrid")

# Create a color palette for the processes
processes = df['Process'].unique()
palette = sns.color_palette("tab10", len(processes))
color_dict = dict(zip(processes, palette))

# Plot the Gantt chart
for product_name, product in df.groupby('Product'):
    for _, row in product.iterrows():
        plt.barh(
            y=row['Product'],
            width=row['End_Time'] - row['Start_Time'],
            left=row['Start_Time'],
            edgecolor='black',
            color=color_dict[row['Process']],
            label=row['Process'] if row['Product'] == 'Product_1' else ""
        )

# Remove duplicate labels in the legend
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys(), title='Process')

plt.xlabel('Time')
plt.ylabel('Product')
plt.title('Production Timeline')
plt.show()env.nowenv.nowenv.nowenv.nowenv.nowenv.now

🔍 Breaking It Down:

  • Simulation Setup: We create three resources - Heater, Processor, Cooler - to represent the production machines.

  • Logging: We log each process's start and end times for every product, making analysis straightforward.

  • Visualisation: The Gantt chart helps us identify potential bottlenecks and see how efficiently products move through the system.

Why This is Useful

SimPy makes it easy to model complex production lines and understand potential problems. For Sebastian, it was about finding the best way to fulfil a weekly production plan with minimal wait times and maximum efficiency. By logging events and visualising the process, we can easily identify inefficiencies and test different optimisations.

Let me know if you have any questions, or if you’ve used SimPy for something similar. I’d love to hear your stories and help out if I can!


r/SimPy • • Sep 11 '24

SimPy helpers - a library to help make SimPy programming easier

2 Upvotes

I have not used this before, but heard it referenced in a PyData lecture on SimPy from the GitHub:

Simpy Helpers

The simpy_helpers package was written to make building simulations and collecting statistics about simulations using the Simpy framework simpler.

simpy_helpers provides 4 main classes:

  1. Entity

  2. Resource

  3. Source

  4. Stats

These building blocks allow you to build complex simulations quickly, while keeping much of the necessary orchestration of simpy components hidden from the user.

Entity, Resource and Source are abstract classes. Read the API documentation to learn which methods are required for building a simulation.

Why Not Just Use Simpy Directly?

Simpy is not that simple to learn and use...

  • Simpy Helpers hides much of this complexity from end users, so they can focus on building simulations instead of orchestrating simpy.

Simpy does not collect statistics for you...

  • Simpy Helpers provides a Stats class which collects relevant statistics about your simulation automatically e.g. utilization of resources