SerializableSimpy package

Submodules

SerializableSimpy.MPI_core module

SerializableSimpy.MPI_utils module

SerializableSimpy.MP_core module

class SerializableSimpy.MP_core.MPGlobalEnv(initial_time: float = 0.0)

Bases: object

env(env: Environment)

Register a local environment.

set_now(now: float)
get_now() float
run(until: float, delta: float)

Run the global simulation until the given time, synchronizing every delta.

SerializableSimpy.MP_utils module

class SerializableSimpy.MP_utils.StoreMP(capacity=inf)

Bases: object

put(obj: Any)
get() Any | None

SerializableSimpy.core module

class SerializableSimpy.core.EventInQueue(time: float, func_ptr: Callable, func_args: Tuple)

Bases: object

Represents an event scheduled in the simulation environment’s priority queue. Events are ordered by their simulation time, enabling time-based execution using a heap (priority queue).

class SerializableSimpy.core.Environment(initial_time: float = 0)

Bases: object

Represents a discrete-event simulation environment.

The environment maintains a priority queue of future events and simulates the progression of time by executing events in order. Processes and callbacks can be registered, and the environment runs until a given time.

process(p: Process)

Register a process to the environment.

Parameters:

p (Process) – A process object to be managed by the environment.

get_now() float

Get the current simulation time.

Returns:

The current simulation time.

Return type:

float

set_now(now: float)

Set the current simulation time.

Parameters:

now (float) – The new simulation time to set.

run(until: float)

Run the simulation until the specified time.

Events are processed in order until the current time reaches until.

Parameters:

until (float) – The simulation time to run until.

timeout(t, func_ptr, func_args)

Schedule an event to occur after a delay.

Parameters:
  • t (float) – The delay (relative time) after which to schedule the event.

  • func_ptr (Callable) – The function to execute at that time.

  • func_args (tuple) – The arguments to pass to the function.

next_event(until) Tuple[float, Callable, Tuple[object]]

Retrieve the next event from the queue.

If the queue is empty, returns a “do nothing” event at the until time.

Parameters:

until (float) – The current simulation horizon.

Returns:

A tuple of (event time, function to call, function arguments).

Return type:

tuple[float, Callable, tuple]

class SerializableSimpy.core.Process

Bases: object

Abstract base class for logical simulation processes.

A process can be attached to a simulation environment and is expected to yield actions that schedule future events. Subclasses must implement the behavior for initialization and yielding.

on_initialize(env: Environment) None

Attach the process to a simulation environment.

This allows the process to be moved between environments — for example, when composing or decomposing simulations into smaller environments.

Parameters:

env (Environment) – The environment to attach the process to.

Raises:

NotImplementedError – Must be implemented in a subclass.

on_yield(*args) None

Called when the process yields control to schedule events.

The process is expected to insert one or more events into self.env.

Parameters:

args (tuple) – Arguments passed during the yield (can be events or commands).

Raises:

NotImplementedError – Must be implemented in a subclass.

class SerializableSimpy.core.Store(capacity: float = inf)

Bases: object

Passive container for producing and consuming concrete objects.

The store accepts items from producers and provides them to consumers via inserting callback events. It behaves like a LIFO queue because items are retrieved with list.pop(). If an item is put and there are waiting consumers, consumers are notified immediately.

on_initialize(env: Environment)

Attach a simulation environment to the store.

Parameters:

env (Environment) – Simulation environment.

on_put(obj: Any)

Put an object into the store.

If the store is not at capacity, the object is appended. If there are waiting consumers, their callbacks are invoked synchronously with available items in LIFO order until either no items or no waiters remain.

Note

When the store is at capacity, the store overflow, this method silently ignores the object (no exception is raised and nothing is queued).

Parameters:

obj (Any) – The object to store.

on_get(pro: Any)

Request an item from the store.

If an item is available, the callback is invoked immediately with the retrieved item (LIFO). Otherwise, the callback is queued and will be invoked when a future on_put provides an item.

Parameters:

pro (callable) – Callback taking a single argument (the retrieved item).

class SerializableSimpy.core.Event(env: Environment)

Bases: object

Lightweight event system for scheduling callbacks.

This class is conceptually similar to simpy.events.Event from SimPy and can be used to model occurrences in a simulation environment that trigger one or more callbacks when completed or failed.

For reference, see the original SimPy implementation: https://gitlab.com/team-simpy/simpy/-/blob/master/src/simpy/events.py?ref_type=heads#L51

Variables:
  • env (Environment) – Simulation environment associated with the event.

  • callbacks (list[tuple[Callable, tuple]]) – List of pending callbacks and their argument tuples.

  • _ok (bool | None) – Boolean indicating event success (True), failure (False), or None if not yet triggered.

on_initialize(env)

Attach a simulation environment to the event.

This replaces the current environment reference.

Parameters:

env (Environment) – Simulation environment.

add_callback(callback: Callable, args=())

Register a callback to be invoked when the event is triggered.

If the event has already succeeded (_ok is True), the callback is invoked immediately with the given arguments. Otherwise, it is queued for later invocation.

Parameters:
  • callback (Callable) – Callable to invoke upon event completion.

  • args (tuple) – Positional arguments to pass to the callback.

on_trigger()

Trigger the event and call all registered callbacks.

Sets _ok to True and invokes all queued callbacks.

succeed()

Mark the event as successful and invoke callbacks.

Ensures API compatibility with SimPy’s succeed().

Returns:

The event itself.

Return type:

Event

fail()

Mark the event as failed and invoke callbacks.

Ensures API compatibility with SimPy’s fail().

Returns:

The event itself.

Return type:

Event

class SerializableSimpy.core.Condition(env: Environment, evaluate: Callable[[Tuple[Event, ...], int], bool], events: Iterable[Event])

Bases: Event

Composite event depending on other events.

A Condition succeeds when a given evaluation function (such as all_events() or any_events()) applied to a set of sub-events returns True. Sub-events must belong to the same Environment.

The Condition class extends Event, so it can be yielded, combined with other events, and will trigger its own callbacks once the condition is satisfied.

Parameters:
  • env (Environment) – The simulation environment in which the condition is evaluated.

  • evaluate (Callable) – Predicate function of the form evaluate(events: tuple[Event, ...], count: int) -> bool that decides when the condition is met.

  • events (Iterable[Event]) – Iterable of sub-events to be monitored.

Raises:

ValueError – If the sub-events do not belong to the same environment.

Example:

cond = Condition(env, Condition.all_events, [evt1, evt2])
cond.add_callback(lambda: print("Both events completed!"))

Note

This class is conceptually similar to simpy.events.Condition.

static all_events(events: Tuple[Event, ...], count: int) bool

Return True if all provided events have been triggered.

Parameters:
  • events (tuple[Event, ...]) – Tuple of events to evaluate.

  • count (int) – Number of events that have been triggered so far.

Returns:

True if count equals the total number of events.

Return type:

bool

static any_events(events: Tuple[Event, ...], count: int) bool

Return True if at least one of the provided events has been triggered.

Parameters:
  • events (tuple[Event, ...]) – Tuple of events to evaluate.

  • count (int) – Number of events that have been triggered so far.

Returns:

True if count > 0 or if events is empty.

Return type:

bool

class SerializableSimpy.core.Resource(env: Environment, capacity: int = 1)

Bases: object

Counting resource with bounded capacity and a waiting queue.

Requests are granted immediately while users < capacity. Otherwise, requests are queued and granted later upon release.

Note

With the current implementation (deque.append() + deque.pop()), queued requests are served in LIFO order. If you want FIFO semantics, replace pop() with popleft().

Parameters:
  • env (Environment) – Simulation environment that manages time and scheduling.

  • capacity (int) – Maximum number of concurrent users.

Variables:
  • env (Environment) – Simulation environment reference.

  • capacity (int) – Maximum number of concurrent users.

  • users (int) – Current number of active users holding the resource.

  • queue (collections.deque[tuple[Callable, tuple]]) – Waiting requests as (callback, args) tuples.

on_initialize(env: Environment) None

Attach (or reattach) a simulation environment.

Parameters:

env (Environment) – Simulation environment.

on_request(what_to_do_when_release: Callable, args: Tuple = ()) None

Request access to the resource.

If capacity is available, the request is granted immediately and the callback is invoked. Otherwise, the request is queued.

Parameters:
  • what_to_do_when_release (Callable) – Callback to execute once access is granted.

  • args (tuple) – Positional arguments passed to the callback.

on_release(what_to_do_when_release: Callable, args: Tuple = ()) None

Release one unit of the resource and serve waiting requests.

Decrements the active user count and grants access to queued requests while capacity is available. Requests are served in LIFO order with the current implementation.

Parameters:
  • what_to_do_when_release (Callable) – (Unused) callback from the releasing user. Included for interface symmetry.

  • args (tuple) – (Unused) arguments from the releasing user.

class SerializableSimpy.core.Interruption(env)

Bases: object

Utility to cancel scheduled callbacks in the environment’s queue.

This helper maintains a list of callbacks to interrupt. When on_interruption() is called, it scans the environment’s future-event queue and removes any queued events whose func_ptr matches a registered callback.

Note

  • This only removes scheduled events; it does not affect callbacks that are already running.

  • Matching is done by function identity (event.func_ptr is callback).

  • The operation runs in \(O(n)\) over env.queue.

on_init(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – The simulation environment.

add_interruption(callback_to_interupt)

Register a callback to be removed from the queue when interrupting.

Parameters:

callback_to_interupt (Callable) – The callback function to cancel if found among queued events.

on_interruption()

Remove all queued events whose callback matches a registered one.

Iterates over env.queue and removes entries whose func_ptr is in callbacks_to_interrupt. Does nothing for callbacks that are not currently scheduled in the queue.

class SerializableSimpy.core.Container(env: Environment, capacity: float = inf, initial: float = 0.0)

Bases: object

Simulated storage container for continuous quantities.

This resource models a container with a finite (or infinite) capacity that holds a certain level of a continuous quantity (e.g., liters of water, units of material). Producers can put amounts into the container and consumers can get amounts from it.

If a request cannot be immediately satisfied (e.g., a put would overflow, or a get would underflow), the request is queued until it becomes possible.

Note

This is similar to simpy.resources.container.Container in SimPy.

on_initialize(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – The simulation environment.

put(amount: float, callback: Callable = None)

Attempt to put an amount into the container.

If there is enough remaining capacity, the amount is added immediately and the optional callback is invoked. If the put cannot be satisfied (because it would exceed capacity), the request is queued in put_waiters for later execution.

After a successful put, this method tries to release any waiting getters that may now be satisfied.

Parameters:
  • amount (float) – Amount to add.

  • callback (Callable or None) – Optional callable to invoke after the put succeeds.

get(amount: float, callback: Callable)

Attempt to get an amount from the container.

If there is enough quantity available, the amount is removed immediately and the callback is invoked. If not enough is available, the request is queued in get_waiters for later execution.

After a successful get, this method tries to release any waiting putters that may now be satisfied.

Parameters:
  • amount (float) – Amount to remove.

  • callback (Callable) – Callable to invoke after the get succeeds.

class SerializableSimpy.core.PriorityResource(env: Environment, capacity: int = 1)

Bases: object

Resource with capacity and priority-based access.

This resource grants access to at most capacity users at a time. Requests beyond the current capacity are queued in a priority queue (lowest numerical priority value is served first).

Within the same priority, requests are served in the order they arrived (FIFO) using a tie-breaker counter.

Note

This is conceptually similar to simpy.resources.resource.PriorityResource in SimPy.

on_initialize(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – The simulation environment.

on_request(callback: callable, args: tuple = (), priority: int = 0)

Request access to the resource.

If the resource has available capacity, the request is granted immediately and the callback is executed. Otherwise, the request is queued with the given priority.

Parameters:
  • callback (callable) – Function to call when the resource becomes available.

  • args (tuple) – Positional arguments for the callback.

  • priority (int) – Request priority (lower values served first).

on_release()

Release the resource and serve the next queued request.

If there are waiting requests, the highest-priority one is granted access immediately. Within the same priority, requests are served in FIFO order.

class SerializableSimpy.core.PreemptiveResource(env, capacity=1)

Bases: object

Resource with capacity, priority scheduling, and preemption.

This resource grants access to at most capacity users at a time. Requests beyond the current capacity are queued in a priority queue (lowest numerical priority value is served first). Within the same priority, requests are served in the order they arrived (FIFO).

Unlike PriorityResource, this resource supports preemption: a higher-priority request may force an active user to release the resource immediately, depending on the preemption rules.

Note

This is conceptually similar to simpy.resources.resource.PreemptiveResource in SimPy.

users

List of active users. Each tuple: (priority, order, name, preemptable, on_preempted_callback)

queue

Waiting requests in the priority queue. Each tuple: (priority, order, preemptable, name, callback, args, on_preempted_callback)

on_initialize(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – The simulation environment.

on_request(name, callback, args=(), priority=0, preempt=True, on_preempted=None)

Request access to the resource.

If the resource has capacity, the request is granted immediately. Otherwise, if preempt is True and there is an active user with lower priority, that user may be preempted. If no preemption occurs, the request is queued.

Parameters:
  • name (str) – Identifier for the requesting user.

  • callback (callable) – Function to call when the resource is granted.

  • args (tuple) – Positional arguments for the callback.

  • priority (int) – Request priority (lower values served first).

  • preempt (bool) – Whether this request can preempt an active user.

  • on_preempted (callable | None) – Callback executed if this request is later preempted.

on_release(name)

Release resource held by a given user and assign to next queued request.

Parameters:

name (str) – Identifier of the user releasing the resource.

class SerializableSimpy.core.FilterStore(env, capacity=inf)

Bases: object

Store for items retrievable by a filter function.

Similar to SimPy’s simpy.resources.store.FilterStore, this store holds items up to a maximum capacity. Consumers request items by providing a filter function which decides whether an available item matches.

If no matching item is available, the request is queued until a future put() adds an item that passes the filter.

Parameters:
  • env (Environment) – Simulation environment.

  • capacity (float) – Maximum number of items in the store. Defaults to infinity.

items

Items currently in the store.

put_queue

Queue of pending puts when the store is full. Each entry is (item, callback).

get_queue

Queue of pending gets with filters when no matching item is available. Each entry is (filter_fn, callback).

on_initialize(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – Simulation environment.

put(item, callback=None)

Insert an item into the store.

If the store has free capacity, the item is stored immediately and any waiting getter whose filter matches it is served. Otherwise, the put request is queued until space becomes available.

Parameters:
  • item (Any) – The item to store.

  • callback (callable | None) – Optional function to call when the put succeeds.

get(filter_fn, callback)

Retrieve an item matching a filter function.

If an item in the store satisfies filter_fn(item) == True, it is removed and returned immediately to the consumer via the callback. Otherwise, the get request is queued until such an item is put.

Parameters:
  • filter_fn (callable) – A callable that takes an item and returns True if it should be retrieved.

  • callback (callable) – Function to call with the retrieved item.

class SerializableSimpy.core.PriorityItem(priority, item)

Bases: object

Wrapper for items stored with an associated priority.

Used by PriorityStore to order items in a heap-based priority queue. Lower priority values indicate higher priority.

Parameters:
  • priority (int | float) – The item’s priority. Lower values are retrieved first.

  • item (Any) – The actual item to store.

class SerializableSimpy.core.PriorityStore(env, capacity=inf)

Bases: object

Store that serves items by priority using a heap.

Items are kept in a min-heap so that the lowest priority value is retrieved first. When the store is full, puts are queued; when it is empty, gets are queued. Each successful put/get attempts to unblock the opposite side.

Note

Items must be comparable for heap ordering. You can store plain numbers/tuples, or wrap arbitrary objects in PriorityItem. (PriorityItem implements __lt__ on its priority.)

Parameters:
  • env (Environment) – Simulation environment.

  • capacity (float) – Maximum number of items in the store (float('inf') for unbounded).

put_queue

list of (item, callback).

Type:

Waiting puts when the store is full

get_queue

list of callbacks.

Type:

Waiting gets when the store is empty

on_initialize(env)

Attach or reattach a simulation environment.

Parameters:

env (Environment) – Simulation environment.

put(item, callback=None)

Put an item in the store or wait if full.

If capacity allows, the item is pushed on the heap and the optional callback is invoked. Afterwards, any waiting getter is served (highest priority item first). If the store is full, the put is queued.

Parameters:
  • item (Any) – The item to store (must be heap-orderable).

  • callback (callable | None) – Optional function called after the put succeeds.

get(callback)

Get the highest-priority item or wait if empty.

If the store is non-empty, pops the minimal item from the heap and invokes the callback. Otherwise, queues the callback until an item becomes available.

Parameters:

callback (callable) – Function to call with the retrieved item.

SerializableSimpy.monitor_event_tracing module

Event tracing utilities for SerializableSimpy.

This module provides helpers to trace the event loop by wrapping Environment.next_event() and recording which callback (event function) is executed at which simulation time.

Reference (SimPy equivalent):

https://simpy.readthedocs.io/en/latest/topical_guides/monitoring.html#event-tracing

SerializableSimpy.monitor_event_tracing.trace(env: Environment, callback: Callable) None

Enable event tracing on an environment.

This function wraps env.next_event so that every time the environment fetches the next scheduled event, callback is invoked with the tuple (t, eid, func) where:

  • t is the event’s scheduled time,

  • eid is the zero-based index of the event pop operation (derived from env._num_pop - 1),

  • func is the function (callback) that will be executed for the event.

The wrapper does not change the event selection; it only observes it.

Parameters:
  • env (Environment) – The simulation environment to instrument.

  • callback (Callable) – A function called as callback(time, event_id, func).

SerializableSimpy.monitor_event_tracing.monitor_list_class(data: list, t: float, eid: int, event: Callable) None

Append (t, eid, class_name) to a list-backed log.

Parameters:
  • data (list) – Target list to append to.

  • t (float) – Event time.

  • eid (int) – Event identifier (zero-based pop count).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_list_object(data: list, t: float, eid: int, event: Callable) None

Append (t, eid, object_name) to a list-backed log.

Parameters:
  • data (list) – Target list to append to.

  • t (float) – Event time.

  • eid (int) – Event identifier (zero-based pop count).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_list_func(data: list, t: float, eid: int, event: Callable) None

Append (t, eid, func_name) to a list-backed log.

Parameters:
  • data (list) – Target list to append to.

  • t (float) – Event time.

  • eid (int) – Event identifier (zero-based pop count).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_dict_class(data: dict, t: float, eid: int, event: Callable) None

Increment the count for class_name in a dict-backed log.

Parameters:
  • data (dict) – Dict accumulator of counts.

  • t (float) – Event time (unused).

  • eid (int) – Event identifier (unused).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_dict_object(data: dict, t: float, eid: int, event: Callable) None

Increment the count for object_name in a dict-backed log.

Parameters:
  • data (dict) – Dict accumulator of counts.

  • t (float) – Event time (unused).

  • eid (int) – Event identifier (unused).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_dict_func(data: dict, t: float, eid: int, event: Callable) None

Increment the count for func_name in a dict-backed log.

Parameters:
  • data (dict) – Dict accumulator of counts.

  • t (float) – Event time (unused).

  • eid (int) – Event identifier (unused).

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_file_class(file, t: float, eid: int, event: Callable) None

Write t<TAB>eid<TAB>class_name to a file-like object.

Parameters:
  • file (IO[str]) – Writable file-like object with write(str).

  • t (float) – Event time.

  • eid (int) – Event identifier.

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_file_object(file, t: float, eid: int, event: Callable) None

Write t<TAB>eid<TAB>object_name to a file-like object.

Parameters:
  • file (IO[str]) – Writable file-like object with write(str).

  • t (float) – Event time.

  • eid (int) – Event identifier.

  • event (Callable) – Event callback (bound method).

SerializableSimpy.monitor_event_tracing.monitor_file_func(file, t: float, eid: int, event: Callable) None

Write t<TAB>eid<TAB>func_name to a file-like object.

Parameters:
  • file (IO[str]) – Writable file-like object with write(str).

  • t (float) – Event time.

  • eid (int) – Event identifier.

  • event (Callable) – Event callback (bound method).