Random Module

Random variate generation and stream management for reproducible simulations.

RandomGenerator

Primary random number generator with 20+ distributions.

class simcraft.RandomGenerator[source]

Bases: object

Random variate generator with common distributions.

Wraps Python’s random module with additional distributions and seeding capabilities for reproducible simulations.

Parameters:

seed (Optional[int]) – Random seed for reproducibility

Examples

>>> rng = RandomGenerator(seed=42)
>>> service_time = rng.exponential(5.0)
>>> batch_size = rng.poisson(10)
>>> priority = rng.choice([1, 2, 3], weights=[0.5, 0.3, 0.2])
__init__(seed=None)[source]

Initialize generator.

Parameters:

seed (int | None)

Return type:

None

property seed: int | None

Get initial seed.

set_seed(seed)[source]

Set new seed.

Parameters:

seed (int) – New seed value

Return type:

None

get_state()[source]

Get current RNG state for checkpointing.

Return type:

tuple

set_state(state)[source]

Restore RNG state from checkpoint.

Parameters:

state (tuple)

Return type:

None

uniform(a=0.0, b=1.0)[source]

Uniform distribution U(a, b).

Parameters:
  • a (float) – Lower bound

  • b (float) – Upper bound

Returns:

Random value in [a, b]

Return type:

float

exponential(mean)[source]

Exponential distribution.

Parameters:

mean (float) – Mean (1/rate)

Returns:

Random exponential value

Return type:

float

normal(mean=0.0, std=1.0)[source]

Normal (Gaussian) distribution.

Parameters:
  • mean (float) – Mean

  • std (float) – Standard deviation

Returns:

Random normal value

Return type:

float

lognormal(mean, std)[source]

Log-normal distribution.

Parameters:
  • mean (float) – Mean of underlying normal

  • std (float) – Standard deviation of underlying normal

Returns:

Random log-normal value

Return type:

float

triangular(low, high, mode=None)[source]

Triangular distribution.

Parameters:
  • low (float) – Minimum value

  • high (float) – Maximum value

  • mode (Optional[float]) – Most likely value (default: midpoint)

Returns:

Random triangular value

Return type:

float

gamma(shape, scale)[source]

Gamma distribution.

Parameters:
  • shape (float) – Shape parameter (k)

  • scale (float) – Scale parameter (theta)

Returns:

Random gamma value

Return type:

float

erlang(k, mean)[source]

Erlang distribution (integer shape gamma).

Parameters:
  • k (int) – Shape parameter (number of phases)

  • mean (float) – Mean of distribution

Returns:

Random Erlang value

Return type:

float

beta(alpha, beta)[source]

Beta distribution.

Parameters:
  • alpha (float) – Alpha parameter

  • beta (float) – Beta parameter

Returns:

Random beta value in [0, 1]

Return type:

float

weibull(shape, scale)[source]

Weibull distribution.

Parameters:
  • shape (float) – Shape parameter (k)

  • scale (float) – Scale parameter (lambda)

Returns:

Random Weibull value

Return type:

float

pareto(alpha, xm=1.0)[source]

Pareto distribution.

Parameters:
  • alpha (float) – Shape parameter

  • xm (float) – Scale parameter (minimum value)

Returns:

Random Pareto value

Return type:

float

randint(a, b)[source]

Uniform integer distribution.

Parameters:
  • a (int) – Lower bound (inclusive)

  • b (int) – Upper bound (inclusive)

Returns:

Random integer in [a, b]

Return type:

int

poisson(lam)[source]

Poisson distribution.

Parameters:

lam (float) – Rate parameter (expected value)

Returns:

Random Poisson value

Return type:

int

geometric(p)[source]

Geometric distribution (number of trials until first success).

Parameters:

p (float) – Success probability

Returns:

Number of trials (>= 1)

Return type:

int

binomial(n, p)[source]

Binomial distribution.

Parameters:
  • n (int) – Number of trials

  • p (float) – Success probability

Returns:

Number of successes

Return type:

int

negative_binomial(r, p)[source]

Negative binomial distribution.

Number of failures before r successes.

Parameters:
  • r (int) – Number of successes required

  • p (float) – Success probability

Returns:

Number of failures

Return type:

int

choice(population, weights=None)[source]

Random selection from population.

Parameters:
  • population (Sequence[T]) – Items to choose from

  • weights (Optional[Sequence[float]]) – Selection weights

Returns:

Selected item

Return type:

T

choices(population, weights=None, k=1)[source]

Random selection with replacement.

Parameters:
  • population (Sequence[T]) – Items to choose from

  • weights (Optional[Sequence[float]]) – Selection weights

  • k (int) – Number of selections

Returns:

Selected items

Return type:

List[T]

sample(population, k)[source]

Random sample without replacement.

Parameters:
  • population (Sequence[T]) – Items to sample from

  • k (int) – Sample size

Returns:

Sampled items

Return type:

List[T]

shuffle(x)[source]

Shuffle list in place.

Parameters:

x (List[T]) – List to shuffle

Return type:

None

shuffled(x)[source]

Return shuffled copy.

Parameters:

x (Sequence[T]) – Sequence to shuffle

Returns:

Shuffled copy

Return type:

List[T]

empirical(values, probabilities)[source]

Empirical discrete distribution.

Parameters:
  • values (Sequence[float]) – Possible values

  • probabilities (Sequence[float]) – Probabilities (must sum to 1)

Returns:

Selected value

Return type:

float

empirical_continuous(breakpoints, probabilities)[source]

Empirical continuous distribution (piecewise linear).

Parameters:
  • breakpoints (Sequence[float]) – Breakpoint values

  • probabilities (Sequence[float]) – Cumulative probabilities at breakpoints

Returns:

Interpolated value

Return type:

float

interarrival_time(rate, time_unit=1.0)[source]

Generate interarrival time for Poisson process.

Parameters:
  • rate (float) – Arrival rate per time unit

  • time_unit (float) – Time unit scale

Returns:

Time until next arrival

Return type:

float

service_time(mean, cv=1.0)[source]

Generate service time with specified coefficient of variation.

Uses gamma distribution to achieve target CV.

Parameters:
  • mean (float) – Mean service time

  • cv (float) – Coefficient of variation (std/mean, default 1.0 = exponential)

Returns:

Service time

Return type:

float

bernoulli(p)[source]

Bernoulli trial.

Parameters:

p (float) – Success probability

Returns:

True with probability p

Return type:

bool

Stream Management

Named streams with checkpointing for variance reduction techniques.

class simcraft.random.streams.RandomStream[source]

Bases: RandomGenerator

Named random stream with checkpointing.

Extends RandomGenerator with stream identification and state management for reproducibility.

Parameters:
  • name (str) – Stream name

  • seed (Optional[int]) – Initial seed

Examples

>>> arrival_stream = RandomStream("arrivals", seed=100)
>>> service_stream = RandomStream("service", seed=200)
>>>
>>> # Save and restore state
>>> state = arrival_stream.checkpoint()
>>> # ... run simulation ...
>>> arrival_stream.restore(state)
__init__(name='', seed=None)[source]

Initialize stream.

Parameters:
  • name (str)

  • seed (int | None)

Return type:

None

property name: str

Get stream name.

checkpoint()[source]

Create checkpoint of current state.

Returns:

Checkpoint data

Return type:

dict

restore(checkpoint)[source]

Restore from checkpoint.

Parameters:

checkpoint (dict) – Checkpoint data

Return type:

None

fork(name=None)[source]

Create a new stream with derived seed.

Parameters:

name (Optional[str]) – Name for new stream

Returns:

New stream

Return type:

RandomStream

class simcraft.random.streams.StreamManager[source]

Bases: object

Manages multiple random streams for a simulation.

Provides centralized stream management, seeding strategies, and synchronization for variance reduction techniques.

Parameters:

base_seed (Optional[int]) – Base seed for stream generation

Examples

>>> manager = StreamManager(base_seed=42)
>>>
>>> # Get or create streams
>>> arrivals = manager.get_stream("arrivals")
>>> service = manager.get_stream("service")
>>>
>>> # Antithetic variates
>>> manager.enable_antithetic()
>>> value1 = arrivals.uniform()  # U
>>> value2 = arrivals.uniform()  # 1-U (antithetic)
__init__(base_seed=None)[source]

Initialize stream manager.

Parameters:

base_seed (int | None)

Return type:

None

property stream_names: List[str]

Get names of all streams.

get_stream(name)[source]

Get or create a named stream.

Parameters:

name (str) – Stream name

Returns:

The stream

Return type:

RandomStream

create_stream(name, seed=None)[source]

Create a new stream with explicit seed.

Parameters:
  • name (str) – Stream name

  • seed (Optional[int]) – Stream seed

Returns:

The new stream

Return type:

RandomStream

reset_all()[source]

Reset all streams to initial state.

Return type:

None

checkpoint()[source]

Checkpoint all streams.

Returns:

Checkpoint data

Return type:

dict

restore(checkpoint)[source]

Restore all streams from checkpoint.

Parameters:

checkpoint (dict) – Checkpoint data

Return type:

None

enable_antithetic()[source]

Enable antithetic variates (for variance reduction).

Return type:

None

disable_antithetic()[source]

Disable antithetic variates.

Return type:

None

set_base_seed(seed)[source]

Set new base seed and regenerate all streams.

Parameters:

seed (int) – New base seed

Return type:

None

class simcraft.random.streams.CommonRandomNumbers[source]

Bases: object

Helper for common random numbers (CRN) technique.

Synchronizes random streams across multiple simulation runs for variance reduction in comparing alternatives.

Examples

>>> crn = CommonRandomNumbers(base_seed=42)
>>>
>>> # Run alternative 1
>>> crn.reset()
>>> results1 = run_simulation(crn.get_stream("arrivals"))
>>>
>>> # Run alternative 2 with same random numbers
>>> crn.reset()
>>> results2 = run_simulation(crn.get_stream("arrivals"))
__init__(base_seed=42)[source]

Initialize CRN helper.

Parameters:

base_seed (int)

Return type:

None

get_stream(name)[source]

Get a synchronized stream.

Parameters:

name (str)

Return type:

RandomStream

save_checkpoint(name='default')[source]

Save current stream states.

Parameters:

name (str)

Return type:

None

load_checkpoint(name='default')[source]

Load saved stream states.

Parameters:

name (str)

Return type:

None

reset()[source]

Reset all streams to initial state.

Return type:

None

Alternative Generators

class simcraft.random.distributions.LCG[source]

Bases: object

Linear Congruential Generator (for compatibility).

Implements the LCG from the WSC challenges for reproducibility.

Parameters:

seed (int) – Initial seed

Examples

>>> lcg = LCG(seed=12345)
>>> value = lcg.uniform()
MULTIPLIER = 1103515245
INCREMENT = 12345
MODULUS = 2147483648
__init__(seed)[source]

Initialize LCG.

Parameters:

seed (int)

Return type:

None

property state: int

Get current state.

uniform()[source]

Generate uniform [0, 1).

Return type:

float

exponential(mean)[source]

Generate exponential with given mean.

Parameters:

mean (float)

Return type:

float