Core Module
The core module contains the fundamental building blocks for discrete event simulation.
Simulation
The main simulation engine with event scheduling and hierarchical composition.
- class simcraft.Simulation[source]
Bases:
objectCore discrete event simulation engine.
The Simulation class provides the fundamental infrastructure for discrete event simulation including event scheduling, time advancement, hierarchical model composition, and execution control.
Features
Efficient event scheduling with priority support
Hierarchical model composition (parent-child sandboxes)
Multiple execution modes (run until, run for, step)
Warmup period handling
Real-time execution support
Event tracing and debugging
Examples
Basic simulation:
>>> class BankSimulation(Simulation): ... def __init__(self): ... super().__init__() ... self.customers_served = 0 ... ... def on_init(self): ... self.schedule(self.customer_arrival, delay=0) ... ... def customer_arrival(self): ... self.customers_served += 1 ... self.schedule(self.customer_arrival, ... delay=self.rng.exponential(5.0)) ... >>> sim = BankSimulation() >>> sim.run(until=100) >>> print(f"Served {sim.customers_served} customers")
Hierarchical composition:
>>> class Server(Simulation): ... def __init__(self, parent: Simulation): ... super().__init__(parent=parent) ... >>> class System(Simulation): ... def __init__(self): ... super().__init__() ... self.server1 = Server(parent=self) ... self.server2 = Server(parent=self)
- __init__(parent=None, config=None, name='')[source]
Initialize simulation.
- Parameters:
parent (Optional[Simulation]) – Parent simulation for hierarchical composition
config (Optional[SimulationConfig]) – Simulation configuration
name (str) – Optional name for the simulation
- Return type:
None
- property rng: RandomGenerator
Get random number generator.
- property state: SimulationState
Get current simulation state.
- property parent: Simulation | None
Get parent simulation.
- property root: Simulation
Get root simulation.
- schedule(action, delay=0.0, at=None, args=(), kwargs=None, tag='', priority=0)[source]
Schedule an event for future execution.
- Parameters:
action (Callable) – Function to execute
delay (float) – Time delay from current time (ignored if ‘at’ is specified)
at (Optional[float]) – Absolute simulation time for execution
args (tuple) – Positional arguments for the action
kwargs (dict) – Keyword arguments for the action
tag (str) – Optional tag for event identification
priority (int) – Priority level (higher = executed first at same time)
- Returns:
The scheduled event (can be used for cancellation)
- Return type:
Examples
>>> sim.schedule(process_arrival, delay=5.0) >>> sim.schedule(process_arrival, at=sim.now + 5.0) >>> sim.schedule(process_arrival, delay=0, priority=10) # High priority
- run(until=None, for_duration=None, events=None)[source]
Run the simulation.
- Parameters:
- Returns:
Self for method chaining
- Return type:
Examples
>>> sim.run(until=100) # Run until time 100 >>> sim.run(for_duration=50) # Run for 50 time units >>> sim.run(events=1000) # Run 1000 events >>> sim.run() # Run until no more events
- step()[source]
Execute a single event.
- Returns:
True if an event was processed, False if no events remain
- Return type:
- warmup(duration=None)[source]
Run warmup period.
- Parameters:
duration (Optional[float]) – Warmup duration (uses config value if not specified)
- Returns:
Self for method chaining
- Return type:
- on_init()[source]
Hook called during initialization.
Override this method to set up initial events and state.
- Return type:
None
- on_end()[source]
Hook called when simulation ends.
Override this method for cleanup and result collection.
- Return type:
None
- on_warmup_end()[source]
Hook called when warmup period ends.
Override this method to reset statistics after warmup.
- Return type:
None
- add_monitor(name, monitor)[source]
Register a monitor/statistics collector.
- Parameters:
name (str) – Monitor name for retrieval
monitor (Any) – Monitor instance
- Return type:
None
Event
Event management and scheduling.
- class simcraft.core.event.Event[source]
Bases:
objectA discrete event scheduled for future execution.
Events are ordered by their scheduled time, with ties broken by their sequence index to ensure deterministic execution order.
- action
The function to call when the event is executed
- Type:
Callable
- owner
The simulation that scheduled this event
- Type:
Examples
>>> def handle_arrival(customer_id: int): ... print(f"Customer {customer_id} arrived") ... >>> event = Event( ... scheduled_time=10.0, ... action=handle_arrival, ... args=(1,), ... index=0 ... ) >>> event.invoke() Customer 1 arrived
- action: Callable[..., Any]
- args: Tuple[Any, ...]
- invoke()[source]
Execute the event action.
- Returns:
The return value of the action, if any
- Return type:
Any
Notes
Cancelled events will not execute and return None.
- cancel()[source]
Cancel this event.
The event will remain in the event list but will not execute when its scheduled time is reached.
- Return type:
None
- __init__(scheduled_time, action, args=<factory>, kwargs=<factory>, owner=None, index=0, tag='', priority=0, cancelled=False)
- class simcraft.core.event.ConditionalEvent[source]
Bases:
objectAn event that executes only when a condition is met.
Useful for events that depend on system state.
- action
The function to call when condition is met
- Type:
Callable
- check_and_execute()[source]
Check condition and execute if met.
- Returns:
True if condition was met and action executed
- Return type:
- __init__(condition, action, args=<factory>, kwargs=<factory>, check_interval=0.1, max_attempts=0, _attempt_count=0)
- class simcraft.core.event.EventList[source]
Bases:
objectEfficient container for managing scheduled events.
Uses sortedcontainers.SortedList for O(log n) insertion and O(1) minimum extraction.
Examples
>>> events = EventList() >>> events.add(Event(scheduled_time=5.0, action=lambda: None, index=0)) >>> events.add(Event(scheduled_time=3.0, action=lambda: None, index=1)) >>> next_event = events.pop_next() >>> print(next_event.scheduled_time) 3.0
- add(event)[source]
Add an event to the list.
- Parameters:
event (Event) – The event to schedule
- Return type:
None
- pop_next()[source]
Remove and return the next event.
- Returns:
The next event to execute, or None if list is empty
- Return type:
Optional[Event]
- peek_next()[source]
Return the next event without removing it.
- Returns:
The next event, or None if list is empty
- Return type:
Optional[Event]
Entity
Simulation entities with lifecycle tracking.
- class simcraft.Entity[source]
Bases:
objectBase class for all simulation entities.
Entities are the objects that flow through and interact within the simulation. They maintain their own state, track timing information, and can carry arbitrary attributes.
- state
Current lifecycle state
- Type:
Examples
>>> class Customer(Entity): ... def __init__(self, priority: int = 0): ... super().__init__() ... self.priority = priority ... >>> customer = Customer(priority=1) >>> customer.set_attribute("vip", True) >>> print(customer.index, customer.get_attribute("vip"))
- state: EntityState = 1
- set_attribute(key, value)[source]
Set a custom attribute.
- Parameters:
key (str) – Attribute name
value (Any) – Attribute value
- Return type:
None
- get_attribute(key, default=None)[source]
Get a custom attribute.
- Parameters:
key (str) – Attribute name
default (Any) – Value to return if attribute not found
- Returns:
Attribute value or default
- Return type:
Any
- class simcraft.core.entity.EntityState[source]
Bases:
EnumStandard entity lifecycle states.
- CREATED = 1
- ACTIVE = 2
- WAITING = 3
- IN_SERVICE = 4
- BLOCKED = 5
- COMPLETED = 6
- DISPOSED = 7
- class simcraft.core.entity.EntityFactory[source]
Bases:
objectFactory for creating entities with consistent configuration.
Examples
>>> factory = EntityFactory(Customer, priority=1) >>> customer1 = factory.create() >>> customer2 = factory.create(vip=True)
- __init__(entity_class, **default_kwargs)[source]
Initialize factory.
- Parameters:
entity_class (Type[Entity]) – Class of entities to create
**default_kwargs – Default keyword arguments for entity creation
- Return type:
None
- class simcraft.core.entity.EntityPool[source]
Bases:
objectPool for reusing entity instances.
Useful for high-frequency entity creation to reduce garbage collection overhead.
Examples
>>> pool = EntityPool(Customer, initial_size=100) >>> customer = pool.acquire() >>> # ... use customer ... >>> pool.release(customer)
Clock
Simulation time management.
- class simcraft.core.clock.Clock[source]
Bases:
objectSimulation clock for centralized time management.
The clock tracks the current simulation time, warmup status, and provides utilities for time conversion and formatting.
- start_datetime
Optional real-world start time for datetime mapping
- Type:
Optional[datetime]
Examples
>>> clock = Clock() >>> clock.advance(1.5) # Advance 1.5 hours >>> print(clock.now) 1.5 >>> print(clock.now_in(TimeUnit.MINUTES)) 90.0
- advance(delta)[source]
Advance the clock by a time delta.
- Parameters:
delta (float) – Time to advance in base time units
- Return type:
None
- advance_to(time)[source]
Advance the clock to a specific time.
- Parameters:
time (float) – Target time in base time units
- Raises:
ValueError – If target time is before current time
- Return type:
None
- property datetime_now: datetime | None
Get current simulation time as real-world datetime.
Returns None if start_datetime is not set.