Simpy

From FOURTEEN1416/academic-agent-toolkit · View interactive version

Simpy is an AI agent skill from the GitHub repository FOURTEEN1416/academic-agent-toolkit. 离散事件仿真(DES):事件、资源、中断、监控、重复运行与热身期、可复现输出分析。用于排队/流程/资源竞争类系统仿真(对应仿真建模赛事 B/C 赛道)。

How to use this skill

Skill file

<!--ACAT-ADAPTED: 收编自 K-Dense-AI/scientific-agent-skills@36d8f13a1e754618794bf42f417884940077b4ae(MIT,fork FOURTEEN1416)。上游兼容性声明与网络/凭据类依赖在本仓库不适用,执行以本机实装版本为准;溯源见 references/UPSTREAM.md。2026-10-16 仿真建模赛补齐批。2026-11-16 重收编:融入上游 v2.72.0(2d2065f)增量——零延迟忙轮询护栏、紧急事件同刻排序说明、监控积分口径与 CLI 指标窗口、PriorityItem 平局语义、pytest 化测试命令;上游文末引用节按本仓惯例未收编。-->

SimPy

Scope

Use this skill for process-based discrete-event models where active entities yield

events and contend for resources: queues, production systems, logistics, networks,

service operations, inventory, and other event-driven systems.

SimPy supplies an event scheduler and modeling primitives. It does not choose a

scientifically valid conceptual model, input distribution, warm-up, run length,

replication count, estimand, or causal interpretation. Treat those as simulation-study

methodology, not SimPy API behavior.

Current release and installation

Reviewed 2026-10-01 against current official documentation and the released source:

4.1.2 points to commit f4381649.

plus PyPy. SimPy has no runtime dependencies.

Create a reproducible environment:

uv venv --python 3.13
source .venv/bin/activate
uv pip install "simpy==4.1.2"
python -c "import importlib.metadata; print(importlib.metadata.version('simpy'))"

Do not silently substitute the latest documentation build: it may describe an

unreleased development revision. Use the versioned 4.1.2 links in

references/sources.md.

Model workflow

  1. Define purpose and estimands. State the decision/question, system boundary,

entities, resources, state, outputs, time units, and terminating event or

steady-state target.

  1. Write a conceptual model first. Record assumptions, distributions,

routing, priorities, initial conditions, and omitted mechanisms.

  1. Implement generators. A SimPy process is an event-yielding Python generator.

Register the generator object with env.process(...).

  1. Bound execution. Give every production run explicit time, entity, event, and

replication caps. Never call env.run() on a model containing an endless process.

A time horizon alone cannot stop an endless yield env.timeout(0) loop: events

keep running at the same simulation time. Add an event-count or no-time-progress

guard, and wait on state-change events instead of zero-delay busy polling.

  1. Separate random streams. Use local RNG instances for logically distinct

stochastic sources; retain a seed manifest.

  1. Instrument deliberately. Observe state after the transition of interest,

close time-weighted intervals at the horizon, and test that monitoring does not

alter event order.

  1. Verify and validate. Test deterministic edge cases, conservation identities,

traces, queue discipline, and analytical benchmarks; compare against system or

expert evidence for the stated purpose.

  1. Run independent replications. Make intervals from replication-level

estimates, not correlated entities within one run.

  1. Report limitations. Include initialization, unfinished entities, run length,

seeds/streams, precision, sensitivity, and validation evidence. Never convert

simulation association into a causal claim.

Read references/simulation-methodology.md before making inferential claims.

Minimal bounded model

import random
import simpy

HORIZON = 480.0
arrival_rng = random.Random(101)
service_rng = random.Random(202)
env = simpy.Environment()
server = simpy.Resource(env, capacity=2)
completed = []

def customer(arrival):
    with server.request() as request:
        yield request
        wait = env.now - arrival
        yield env.timeout(service_rng.expovariate(1 / 6.0))
    completed.append((env.now, wait))

def arrivals():
    for _ in range(10_000):  # Entity cap.
        delay = arrival_rng.expovariate(1 / 4.0)
        if env.now + delay >= HORIZON:
            return
        yield env.timeout(delay)
        env.process(customer(env.now))

env.process(arrivals())
env.run(until=HORIZON)

The numeric horizon is half-open: normal events scheduled exactly at 480.0 are

not processed. Report unfinished entities rather than silently treating them as

completed observations.

Core semantics

Environment and deterministic ordering

Environment is single-threaded. The queue is ordered by simulation time, event

priority, then a strictly increasing event ID. Same-time, same-priority events are

therefore processed FIFO in scheduling order. Model processes may represent

concurrency, but callbacks execute sequentially and deterministically.

This orders the events currently queued. A callback can insert an urgent event at

the current time, so a valid processing trace need not have globally increasing

priority or event IDs within a timestamp.

env.run(until=number) and env.run(until=event) are not interchangeable at

boundaries:

that exact time.

Other same-time ordering depends on priority and scheduling order.

StopSimulation by rescheduling the target. Consequently, after

env.run(until=target), target.processed can remain False until one more

step()/run() even though its value was returned. Do not use processed as the

sole post-run completion test.

See references/events.md and references/monitoring.md.

Event, Timeout, Process, and Condition

succeed(value) or fail(exception) triggers it once.

manually succeeded again.

yielded event value. Returning from the generator succeeds the Process with that

return value. Uncaught exceptions fail it.

dict-like mapping from event objects to their values. Test membership using

the original event objects; do not assume a scalar result.

requests when abandoning them; ordinary timeouts remain scheduled.

Interrupts

process.interrupt(cause) schedules an urgent interruption that throws

simpy.Interrupt into the target generator. Catch it around the yielded work that

may be interrupted, inspect interrupt.cause, update remaining work, then either

resume, re-yield the original event, or terminate.

Interrupting a process removes its resume callback from its current target; it does

not cancel that target event. A process cannot interrupt itself or a terminated

process. See references/process-interaction.md.

Shared resources

| Type | Semantics |

|---|---|

| Resource | FIFO semaphore-like usage slots |

| PriorityResource | Queued requests sorted by lower numeric priority first |

| PreemptiveResource | Priority queue plus optional preemption of a current user |

| Container | Homogeneous numeric level; put/get wait for capacity/material |

| Store | FIFO Python objects |

| FilterStore | First available item satisfying the request's predicate |

| PriorityStore | Comparable items returned in priority order |

Use a request context manager:

def job(env, resource):
    with resource.request() as request:
        yield request
        yield env.timeout(3)

On exit it releases an acquired request or cancels a still-pending one, including

during exception unwinding. For a manually retained pending put/get/request,

call cancel() if an interrupt or timeout makes the process abandon it.

PreemptiveResource.request(priority=..., preempt=True) uses lower numbers as

higher priority. The preempted process receives an Interrupt whose cause is a

Preempted object: cause.by is the preempting Process,

cause.usage_since is when use began, and cause.resource is the resource.

Queued priority takes precedence over the preempt flag; mixing preempting and

non-preempting requests needs explicit tests.

Read references/resources.md for blocked operations, queue rules, and examples.

Monitoring and stepping

Prefer explicit domain observations at state transitions. For generic resource

monitoring, wrappers or subclasses can inspect count, queue, level, items,

put_queue, and get_queue. For event tracing, schedule() and step() are the

central hooks.

Queue measurements are timing-sensitive:

callback can all differ at the same simulation timestamp.

post-transition state path and divide by elapsed time.

Pin SimPy, isolate the instrumentation, and regression-test after upgrades.

Use scripts/resource_monitor.py and references/monitoring.md.

Real-time execution

simpy.rt.RealtimeEnvironment(initial_time=0, factor=1.0, strict=True) maps one

simulation unit to factor wall-clock seconds. In strict mode, step()/run()

raises RuntimeError when computation falls behind. strict=False tolerates lag;

it does not restore timing accuracy. Develop logic with Environment, then run

separate timing tests with generous platform-aware tolerances. See

references/real-time.md.

Bundled safe CLIs

All CLIs use a fixed built-in queue model or summarize local artifacts. They reject

unknown JSON keys, URLs, symlinks, non-finite numbers, oversized inputs, and

unbounded time/events/entities/replications. They never evaluate config text,

execute user Python, import plugins, or call a network service.

# Inspect all options.
python skills/simpy/scripts/bounded_queue_scenario.py --help
python skills/simpy/scripts/replication_runner.py --help
python skills/simpy/scripts/event_trace_summary.py --help
python skills/simpy/scripts/validate_simulation_config.py --help

# Deterministic built-in scenario.
python skills/simpy/scripts/bounded_queue_scenario.py

# Independent replications with replication-level Student-t intervals.
python skills/simpy/scripts/replication_runner.py

# Validate only; no simulation runs.
python skills/simpy/scripts/validate_simulation_config.py config.json

The replication runner refuses one-replication intervals. Its intervals quantify

Monte Carlo uncertainty under the configured model; they neither validate the model

nor identify causal effects. See references/cli-guide.md.

Schema 1.2 reports explicit metric windows: throughput counts all departures during

[warm_up, horizon), loss uses arrivals/rejections in that same window, and customer

means use post-warm-up arrivals completed before the horizon. These customer means

remain vulnerable to completion censoring. The scripts require the pinned SimPy

version because tracing depends on its scheduler internals.

Testing

Use deterministic unit tests for ordering, boundary times, conditions, interrupts,

all resource disciplines, conservation, event/entity limits, seed reproducibility,

and monitor non-interference. Add stochastic tests only as broad distributional

checks with fixed seeds; avoid brittle exact sample estimates.

Run the skill's suite in the exact pinned environment without bytecode artifacts:

PYTHONDONTWRITEBYTECODE=1 uv run --isolated --no-project \
  --python 3.13 --with "simpy==4.1.2" --with pytest \
  python -m pytest tests/simpy -q

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.