Statistics Module
Data collection and analysis components for simulation output.
Counter
Event counting with rate calculation.
- class simcraft.Counter[source]
Bases:
objectCounter for discrete events.
Tracks the number of occurrences and calculates rates.
- Parameters:
sim (Optional[Simulation]) – Parent simulation for rate calculations
name (str) – Counter name
Examples
>>> counter = Counter(sim, name="arrivals") >>> counter.increment() >>> counter.increment(5) >>> print(counter.value) 6 >>> print(counter.rate) # per time unit
- class simcraft.statistics.counter.WindowedCounter[source]
Bases:
objectCounter that tracks values over a sliding time window.
Useful for calculating rates over recent time periods.
- Parameters:
sim (Simulation) – Parent simulation
window_size (float) – Size of sliding window in time units
name (str) – Counter name
Examples
>>> counter = WindowedCounter(sim, window_size=60.0, name="arrivals_per_hour") >>> counter.increment() >>> # ... time passes ... >>> print(counter.window_rate) # Rate over last 60 time units
- __init__(sim, window_size, name='')[source]
Initialize windowed counter.
- Parameters:
sim (Simulation)
window_size (float)
name (str)
- Return type:
None
Tally
Discrete observation collector with statistical analysis using Welford’s algorithm.
- class simcraft.Tally[source]
Bases:
objectCollects discrete observations and calculates statistics.
Efficiently calculates running statistics without storing all observations (unless keep_history is True).
- Parameters:
sim (Optional[Simulation]) – Parent simulation
name (str) – Tally name
keep_history (bool) – Whether to store all observations
Examples
>>> tally = Tally(name="service_time") >>> for time in service_times: ... tally.observe(time) >>> print(tally.mean, tally.std)
- observe(value)[source]
Record an observation.
- Parameters:
value (float) – Observed value
- Return type:
None
- observe_batch(values)[source]
Record multiple observations.
- Parameters:
values (List[float]) – Observed values
- Return type:
None
- percentile(p)[source]
Calculate percentile from stored history.
- Parameters:
p (float) – Percentile (0-100)
- Returns:
Percentile value
- Return type:
- Raises:
ValueError – If history not kept or empty
- __init__(name='', keep_history=False, _sim=None, _count=0, _mean=0.0, _m2=0.0, _min=inf, _max=-inf, _sum=0.0, _history=<factory>)
- class simcraft.statistics.tally.BatchTally[source]
Bases:
TallyTally that groups observations into batches for analysis.
Useful for batch means analysis and detecting initialization bias.
TimeSeries
Time-weighted statistics collection (equivalent to O2DES HourCounter).
- class simcraft.TimeSeries[source]
Bases:
objectTime-weighted statistics collector (HourCounter equivalent).
Tracks a value that changes over time and calculates time-weighted statistics like average count, utilization, and average duration.
- Parameters:
sim (Simulation) – Parent simulation for time tracking
name (str) – Time series name
initial_value (float) – Initial value
keep_history (bool) – Whether to store value history
Examples
>>> ts = TimeSeries(sim, name="queue_length") >>> ts.observe_change(1) # Entity enters queue >>> ts.observe_change(1) # Another entity >>> # ... time passes ... >>> ts.observe_change(-1) # Entity leaves >>> print(ts.average_value) # Time-weighted average >>> print(ts.average_duration) # Average time per entry
- __init__(sim, name='', initial_value=0.0, keep_history=False)[source]
Initialize time series.
- Parameters:
sim (Simulation)
name (str)
initial_value (float)
keep_history (bool)
- Return type:
None
- property average_duration: float
Get average duration per entry.
For counting values (queue length), this gives the average time an item spends in the system.
- property utilization: float
Get utilization ratio (fraction of time value > 0).
For capacity tracking, this gives the busy ratio.
- observe_value(value)[source]
Set value directly (observe absolute value).
- Parameters:
value (float) – New value
- Return type:
None
- histogram(bins=10, min_val=None, max_val=None)[source]
Calculate time-weighted histogram from history.
- class simcraft.statistics.time_series.CapacityTimeSeries[source]
Bases:
TimeSeriesTimeSeries specialized for capacity tracking.
Tracks busy/idle states for a resource with fixed capacity.
- Parameters:
sim (Simulation) – Parent simulation
capacity (int) – Total capacity
name (str) – Time series name
- __init__(sim, capacity, name='')[source]
Initialize capacity time series.
- Parameters:
sim (Simulation)
capacity (int)
name (str)
- Return type:
None
Monitor
Unified data collection with multiple metric types.
- class simcraft.Monitor[source]
Bases:
objectGeneral-purpose data collection and monitoring.
Provides a unified interface for tracking counters, tallies, and time series, with support for data export and reporting.
- Parameters:
sim (Simulation) – Parent simulation
name (str) – Monitor name
Examples
>>> monitor = Monitor(sim, name="performance") >>> >>> # Add collectors >>> monitor.add_counter("arrivals") >>> monitor.add_tally("service_time") >>> monitor.add_time_series("queue_length") >>> >>> # Record data >>> monitor.counters["arrivals"].increment() >>> monitor.tallies["service_time"].observe(5.2) >>> monitor.time_series["queue_length"].observe_change(1) >>> >>> # Get report >>> report = monitor.report()
- __init__(sim, name='')[source]
Initialize monitor.
- Parameters:
sim (Simulation)
name (str)
- Return type:
None
- property time_series: Dict[str, TimeSeries]
Get all time series.
- add_time_series(name, initial_value=0.0, keep_history=False)[source]
Add a time series.
- Parameters:
- Returns:
The created time series
- Return type:
- add_custom_metric(name, calculator)[source]
Add a custom metric.
- Parameters:
name (str) – Metric name
calculator (Callable) – Function that returns the metric value
- Return type:
None
- get_time_series(name)[source]
Get time series by name.
- Parameters:
name (str)
- Return type:
TimeSeries | None
- log_event(event_type, data=None)[source]
Log an event.
- Parameters:
event_type (str) – Type of event
data (Any) – Event data
- Return type:
None
- report()[source]
Generate a summary report.
- Returns:
Dictionary with all statistics
- Return type:
Dict[str, Any]
- to_dataframe()[source]
Export time series data as pandas DataFrame.
- Returns:
DataFrame with time series data
- Return type:
pd.DataFrame
- Raises:
ImportError – If pandas is not available
- class simcraft.statistics.monitor.SimulationRecorder[source]
Bases:
objectRecords simulation state at regular intervals.
Useful for generating time-series plots and animations.
- Parameters:
sim (Simulation) – Parent simulation
interval (float) – Recording interval
- __init__(sim, interval=1.0)[source]
Initialize recorder.
- Parameters:
sim (Simulation)
interval (float)
- Return type:
None
- add_collector(name, collector)[source]
Add a data collector.
- Parameters:
name (str) – Data series name
collector (Callable) – Function that returns the current value
- Return type:
None