### Initialize Environment and Imports Source: https://github.com/a-herzog/queuesim/blob/master/example_analytic_erlang_c_ext.ipynb Setup the necessary modules for Erlang C calculations and plotting. ```python # Erlang module from queuesim.analytic import erlang_c_ext_table # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Defining general plot style plt.style.use('seaborn-v0_8') percent_formater = formater.PercentFormatter(xmax=1, decimals=0) ``` -------------------------------- ### Manual Queue Simulation Setup Source: https://github.com/a-herzog/queuesim/blob/master/README_simulation.md Configures a simulation pipeline using Source, Process, and Dispose stations. ```python import queuesim from queuesim.stations import Source, Process, Dispose from queuesim.random_dist import exp as exp_dist from queuesim.models import mmc_results count = 100_000 get_i = exp_dist(100) get_s = exp_dist(80) c = 1 simulator = queuesim.Simulator() source = Source(simulator, count, get_i) process = Process(simulator, get_s, c) dispose = Dispose(simulator) source.set_next(process) process.set_next(dispose) simulator.run() model={'Source': source, 'Process': process, 'Dispose': dispose} print(mmc_results(model)) ``` -------------------------------- ### Setup Imports and Plotting Style Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_random_numbers.ipynb Initializes necessary libraries for mathematical operations, plotting, and statistical recording. ```python import math from typing import Union, Callable # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Generating pseudo random numbers import queuesim.random_dist as rnd # Recording statistics from queuesim.statistics import RecordDiscrete # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Importing queuesim modules Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center.ipynb Initial setup of the simulation environment, including station types, random distributions, and plotting tools. ```python # Simulator from queuesim import Simulator # Station types from queuesim.stations import Source, Process, Decide, Delay, Dispose # Pseudo random number generators from queuesim.random_dist import exp as dist_exp # Print results from queuesim.models import call_center_results # Plot model from queuesim import build_graph import networkx as nx import matplotlib.pyplot as plt # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Running the two-station simulation Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Setup and execution of a simulation with two stations where clients are routed randomly. ```python # Simulator simulator = Simulator() # Stations source = Source(simulator, count, inter_arrival_time) decide = Decide(simulator) process1 = Process(simulator, process_time, c) process2 = Process(simulator, process_time, c) dispose = Dispose(simulator) # Link stations source.set_next(decide) decide.add_next(process1, 1) decide.add_next(process2, 1) process1.set_next(dispose) process2.set_next(dispose) # Run simulation simulator.run() # Results name = "2 queues, random" enq = process1.statistic_queue_length.mean + process2.statistic_queue_length.mean en = process1.statistic_wip.mean + process2.statistic_wip.mean enq_dict[name] = enq en_dict[name] = en print("E[NQ]=", round(enq, 2), sep="") print("E[N]=", round(en, 2), sep="") ``` -------------------------------- ### Configure Batch Processing in Process Source: https://github.com/a-herzog/queuesim/blob/master/README_batch.md Set the b parameter in the Process constructor to define the batch size for service; the station waits until b clients are available before starting service. ```python import queuesim from queuesim.stations import Process, ... from queuesim.random_dist import exp as exp_dist simulator = queuesim.Simulator() # Serve clients in batches of size 3 process = Process(simulator, getS = exp_dist(80), c = 1, b = 3) ``` -------------------------------- ### Importing Libraries and Setting Up Simulation Parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple1.ipynb Initializes the simulation environment and defines the cost parameters for waiting time and operator count. ```python # Processing results arrays import numpy as np # Simulator from queuesim.tools import SimProcess, run_parallel # Station types from queuesim.models import mmc_model # Plot model import matplotlib.pyplot as plt # Defining general plot style plt.style.use('seaborn-v0_8') ``` ```python # Arrivals to be simulated count = 100_000 # Arrival process mean_I = 50 # Service process mean_S = 600 # Costs cost_waiting = 10 # Costs per waiting second cost_c = 120 # Costs per operator ``` -------------------------------- ### Initialize and run a simulation Source: https://github.com/a-herzog/queuesim/blob/master/README.md Basic structure for setting up a simulator instance and executing the simulation loop. ```python import queuesim simulator = queuesim.Simulator() # Define stations here, link stations to each other and to the simulator simulator.run() # Process statistic results here ``` -------------------------------- ### Initialize base queueing model Source: https://github.com/a-herzog/queuesim/blob/master/README_control.md Sets up the simulator, source, process stations, and disposal for a basic queueing system. ```python import queuesim from queuesim.stations import Source, Process, Dispose from queuesim.random_dist import exp as exp_dist from queuesim.models import mmc_results count = 100_000 get_i = exp_dist(100) get_s = exp_dist(160) c1 = 1 c2 = 1 simulator = queuesim.Simulator() source = Source(simulator, count, get_i) decide = ... # Select decide mode process2 = Process(simulator, get_s, c1) process2 = Process(simulator, get_s, c1) dispose = Dispose(simulator) source.set_next(decide) ... # Setup decide mode process1.set_next(dispose) process2.set_next(dispose) simulator.run() ``` -------------------------------- ### Configure a Source station Source: https://github.com/a-herzog/queuesim/blob/master/README.md Create a Source station to introduce clients into the simulation network with defined inter-arrival times. ```python import queuesim import queuesim.stations simulator = queuesim.Simulator() count = 100_000 # Number of arrivals to be simulated get_i = ... # string (to be evaluated) or lambda expression to generate inter-arrival times source = queuesim.stations.Source(simulator, count, get_i) next_station_in_queueing_network = ... source.set_next(next_station_in_queueing_network) ``` -------------------------------- ### Running the Optimizer Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple2.ipynb Configures the initial guess and bounds, then executes the BOBYQA optimization algorithm. ```python # Initial solution x0 = np.array([15]) # Search range a = np.array([14]) b = np.array([24]) # Running BOBYQA soln = pybobyqa.solve(f, x0, bounds=(a, b)) ``` -------------------------------- ### Initializing simulation stations Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_network.ipynb Creates the simulator instance and defines the source, process, and dispose stations. ```python simulator = Simulator() source = Source(simulator, count, dist_exp(mean_i)) process1 = Process(simulator, dist_exp(mean_s1), c1) process2 = Process(simulator, dist_exp(mean_s2), c2) dispose = Dispose(simulator) ``` -------------------------------- ### Configure and Link Simulation Stations Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities2.ipynb Initializes the simulator, configures sources and processes, and links the station network. ```python # Define parameters get_i = dist_exp(mean_i * 2) # average inter-arrival time mean_i is for both client types together. mean_i*2 is for a single client type. get_s = dist_exp(mean_s) # Create and configure stations simulator = Simulator() source1 = Source(simulator, round(count / 2), get_i, client_type_name="ClientsA") source2 = Source(simulator, round(count / 2), get_i, client_type_name="ClientsB") process = Process(simulator, get_s, c, getPriority=priority) decide = DecideClientType(simulator) dispose1 = Dispose(simulator) dispose2 = Dispose(simulator) # Link stations source1.set_next(process) source2.set_next(process) process.set_next(decide) decide.set_next("ClientsA", dispose1) decide.set_next("ClientsB", dispose2) ``` -------------------------------- ### Configure a process station with impatience Source: https://github.com/a-herzog/queuesim/blob/master/README_impatience.md Demonstrates setting up a process station with a waiting time tolerance and defining a next station for canceled clients. ```python import queuesim from queuesim.stations import Source, Process, Dispose from queuesim.random_dist import exp as exp_dist from queuesim.models import mmc_results count = 100_000 get_i = exp_dist(100) get_s = exp_dist(80) get_Nu= exp_dist(600) # Waiting time tolerance c = 1 simulator = queuesim.Simulator() source = Source(simulator, count, get_i) process = Process(simulator, get_s, c, getNu=getNu) dispose = Dispose(simulator) source.set_next(process) process.set_next(dispose) process.set_next_cancel(dispose) # Canceled clients leave the system just as successful clients simulator.run() ``` -------------------------------- ### Initialize Simulation Environment Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center_series.ipynb Imports necessary modules for data handling, plotting, simulation, and analytic calculations. ```python # Data collection import pandas as pd # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Simulation from queuesim import SimProcess, run_parallel from queuesim.models import impatience_and_retry_model_build # Analytic calculation from queuesim.analytic import erlang_c_table, erlang_c_ext_table # Defining general plot style plt.style.use('seaborn-v0_8') percent_formater = formater.PercentFormatter(xmax=1, decimals=0) ``` -------------------------------- ### Executing the optimization Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_complex2.ipynb Configures the initial guess and bounds, then runs the BOBYQA solver. ```python # Initial solution x0 = np.array([0.75]) # Search range a = np.array([0.5]) b = np.array([0.99]) # Running BOBYQA soln = pybobyqa.solve(minimize_f, x0, bounds=(a, b)) # Actually correct, but then the optimization runs endlessly (==">5Min"): objfun_has_noise=True ``` -------------------------------- ### Create Simulation Stations Source: https://github.com/a-herzog/queuesim/blob/master/README_simulation.md Instantiate Source, Process, and Dispose stations by passing the simulator instance and specific configuration parameters. ```python from queuesim.stations import Source, Process, Dispose source = Source(simulator, count, get_i) process = Process(simulator, get_s, c) dispose = Dispose(simulator) ``` -------------------------------- ### Building and Running the Model Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_course.ipynb Constructs the M/M/c model with recording enabled and executes the simulation. ```python # Build model model = mmc_model(mean_i, mean_s, c, count, record_values=True) # Run simulation simulator = get_simulator_from_model(model) simulator.run() ``` -------------------------------- ### Initialize Simulation Environment Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_complex1.ipynb Imports necessary libraries and configures the plotting style for the simulation analysis. ```python # Processing results arrays import numpy as np # Simulator from queuesim.tools import SimProcess, run_parallel # Station types from queuesim.models import mmc_model # Plot model import matplotlib.pyplot as plt # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Initializing simulation stations Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center.ipynb Creating the simulation objects for the defined model components. ```python simulator = Simulator() source = Source(simulator, count, get_i, get_ib) process = Process(simulator, get_s, c, get_nu, get_s2, K, b, LIFO) forwarding = Decide(simulator) retry = Decide(simulator) delay = Delay(simulator, get_retry_delay) dispose = Dispose(simulator) ``` -------------------------------- ### Initialize Environment and Imports Source: https://github.com/a-herzog/queuesim/blob/master/example_analytic_ac_approx.ipynb Imports the necessary analytic functions and plotting libraries, and configures the default plot style. ```python # Erlang module from queuesim.analytic import ac_approx_table # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Defining general plot style plt.style.use('seaborn-v0_8') percent_formater = formater.PercentFormatter(xmax=1, decimals=0) ``` -------------------------------- ### Build a manual M/M/c model Source: https://github.com/a-herzog/queuesim/blob/master/README.md Constructs a simulation model by explicitly defining Source, Process, and Dispose stations and connecting them. ```python import queuesim from queuesim.stations import Source, Process, Dispose from queuesim.random_dist import exp as exp_dist count = 100_000 # Number of arrivals to be simulated get_i = exp_dist(100) # exponential distribution with mean E[I]=100 get_s = exp_dist(80) # exponential distribution with mean E[S]=80 c = 1 # One operator in this model # The simulator simulator = queuesim.Simulator() # Configuring the stations source = Source(simulator, count, get_i) process = Process(simulator, get_s, c) dispose = Dispose(simulator) # Connecting the stations source.set_next(process) process.set_next(dispose) # Running the simulation simulator.run() ``` -------------------------------- ### Importing Queuesim modules Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities1.ipynb Initializes the environment by importing necessary simulation models and random number generators. ```python # Generating random priorities from random import random as random_float # Simulation from queuesim.models import mmc_model_priorities, get_simulator_from_model ``` -------------------------------- ### Configure Batch Arrivals in Source Source: https://github.com/a-herzog/queuesim/blob/master/README_batch.md Use the getB parameter in the Source constructor to define fixed or variable batch sizes for incoming clients. ```python import queuesim from queuesim.stations import Source, ... from queuesim.random_dist import exp as exp_dist simulator = queuesim.Simulator() # Fixed arrival batch size of 5 fixed_batch_size = lambda: 5 source = Source(simulator, count = 100_000, getI = exp_dist(100), getB = fixed_batch_size) # Random batch size in range from 3 to 5 (including both limits) from random import randint variable_batch_size = lambda: randint(3, 5) source = Source(simulator, count = 100_000, getI = exp_dist(100), getB = variable_batch_size) ``` -------------------------------- ### Running the M/M/c simulation Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_simple.ipynb Builds the model, executes the simulation, and prints the resulting performance metrics. ```python # Build model model = mmc_model(mean_i, mean_s, c, count) # Run simulation simulator = get_simulator_from_model(model) %time simulator.run() # Show results print(mmc_results(model)) ``` -------------------------------- ### Importing required modules Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_simple.ipynb Initializes the environment by importing plotting tools, simulation components, and analytic functions. ```python # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Simulation from queuesim.models import mmc_model, mmc_results, get_simulator_from_model # Analytic calculation from queuesim.analytic import erlang_c # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Run the simulation Source: https://github.com/a-herzog/queuesim/blob/master/README_simulation.md Execute the simulation after stations are created and connected. ```python simulator.run() ``` -------------------------------- ### Building and running the network model Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_network.ipynb Constructs the network model using the defined stations and matrices, then executes the simulation. ```python build_network_model([source],[process1,process2],[dispose],connections1,connections2) ``` ```python simulator.run() ``` -------------------------------- ### Configure a Dispose station Source: https://github.com/a-herzog/queuesim/blob/master/README.md Create a Dispose station to remove clients from the system and record their final statistics. ```python import queuesim import queuesim.stations simulator = queuesim.Simulator() get_s = ... # string (to be evaluated) or lambda expression to generate the service times c = 1 # Number of parallel operators dispose = queuesim.stations.Dispose(simulator) ``` -------------------------------- ### Executing the simulation loop Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_GGc.ipynb Iterates through arrivals to track server availability and calculate total waiting time. ```python waiting_sum = 0 server_free_at = np.zeros(c) for (time, service_time) in zip(arrival_times, service_times): index = np.argmin(server_free_at) # Find next free server service_start = max(time, server_free_at[index]) waiting_sum += service_start - time server_free_at[index] = service_start + service_time # Store new time when server gets idle again ``` -------------------------------- ### Build a queueing network model Source: https://github.com/a-herzog/queuesim/blob/master/README_networks.md Uses build_network_model to define station transitions based on source, process, and dispose objects. ```python from queuesim import Simulator from queuesim.stations import Source, Process, Dispose simulator = Simulator() source = Source(simulator, ...) process1 = Process(simulator, ...) process2 = Process(simulator, ...) dispose = Dispose() connections1=[[0.8, 0.2]] # 80% of the clients go to process1, 20% to process2 connections2=[[0.0, 0.3, 0.7], [1, 0, 0]] # Most clients (70%) leave system after process1, some (30%) go to process2; all clients from process2 go to process1 build_network_model([source], [process1,process2], [dispose], connections1, connections2) simulator.run() ``` -------------------------------- ### Configure a Process station Source: https://github.com/a-herzog/queuesim/blob/master/README.md Create a Process station to handle client queues and service operations with configurable parallel operators. ```python import queuesim import queuesim.stations simulator = queuesim.Simulator() get_s = ... # string (to be evaluated) or lambda expression to generate the service times c = 1 # Number of parallel operators process = queuesim.stations.Process(simulator, get_s, c) next_station_in_queueing_network = ... process.set_next(next_station_in_queueing_network) ``` -------------------------------- ### Run simulations in parallel Source: https://github.com/a-herzog/queuesim/blob/master/README_parallelization.md Demonstrates creating a list of SimProcess objects and executing them concurrently using run_parallel. ```python from queuesim import SimProcess, run_parallel from queuesim.models import mmc_model # Input parameters mean_i = 100 mean_s_range = range(70, 93) c = 1 count = 100_000 # Generate processes processes=[SimProcess(mmc_model(mean_i, mean_s, c, count)) for mean_s in mean_s_range] # Run processes and wait for termination of all processes models, simulators = run_parallel(processes) # Get a list of the average queue lengths of the different models ENQ = [model['Process'].statistic_queue_length.mean for model in models] ``` -------------------------------- ### Initializing result dictionaries Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Dictionaries used to store simulation metrics. ```python enq_dict = {} en_dict = {} ``` -------------------------------- ### Configuring simulation parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center.ipynb Defining the arrival, service, and system parameters for the call center model. ```python # Arrivals to be simulated count = 100_000 # Arrival process mean_i = 100 get_i = dist_exp(mean_i) get_ib = None # Batch arrivals # Service process mean_s = 80 get_s = dist_exp(mean_s) b = 1 # Service batch size # Post-processing times get_s2 = None # Impatience mean_nu = 900 get_nu = None # None = no impatience # Retry process retry_rate = 0 mean_retry_delay = 900 get_retry_delay = dist_exp(mean_retry_delay) # Number of operators c = 1 # System size K = -1 # -1 stands for "unlimited" # FIFO or LIFO client selection LIFO = False # Forwarding forwarding_rate = 0 ``` -------------------------------- ### Importing Simulation Modules Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_course.ipynb Initializes the plotting environment and imports necessary simulation components from queuesim. ```python # Plotting modules import matplotlib.pyplot as plt # Simulation from queuesim.models import mmc_model, get_simulator_from_model # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Calculate performance indicators with Erlang C Source: https://github.com/a-herzog/queuesim/blob/master/README.md Instantiate an Erlang C model with arrival rate, service rate, and number of servers to access performance metrics. ```python from queuesim.analytic import erlang_c model=erlang_c(l, mu, c) # Parameters: lambda=1/E[I], mu=1/E[S], c print("Workload a=", model.a) print("Utilization rho=", model.rho) print("Average queue length E[N_Q]=", model.ENQ) print("Average number of clients in the system E[N]=", model.EN) print("Average waiting time E[W]=", model.EW) print("Average residence time E[V]=", model.EV) ``` -------------------------------- ### Running the simulation Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center.ipynb Executing the simulation and printing the results. ```python simulator.run() ``` ```python print(call_center_results(source, process, forwarding, retry, delay, dispose, simulator)) ``` -------------------------------- ### Simulate single station with batch processing Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Configures a simulation with a source, a process station with batch processing enabled, and a dispose station. ```python # Simulator simulator = Simulator() # Stations source = Source(simulator, count, inter_arrival_time) process = Process(simulator, process_time, c, b=2) dispose = Dispose(simulator) # Link stations source.set_next(process) process.set_next(dispose) # Run simulation simulator.run() # Results name = "1 queue, batch processing" enq = process.statistic_queue_length.mean en = process.statistic_wip.mean enq_dict[name] = enq en_dict[name] = en print("E[NQ]=", round(enq, 2), sep="") print("E[N]=", round(en, 2), sep="") ``` -------------------------------- ### Importing required modules Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Initial imports for random number generation, data collection, and simulation components. ```python # Generating integer pseudo random numbers from random import randint # Collecting results import pandas as pd # Simulation from queuesim.stations import Source, Decide, DecideCondition, Process, Dispose from queuesim import Simulator from queuesim.random_dist import exp as exp_dist ``` -------------------------------- ### Simulate two stations with shortest-queue routing Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Configures a simulation where incoming clients are routed to the station with the shortest current queue length. ```python # Simulator simulator = Simulator() # Stations source = Source(simulator, count, inter_arrival_time) decide = DecideCondition(simulator) process1 = Process(simulator, process_time, c) process2 = Process(simulator, process_time, c) dispose = Dispose(simulator) def shortest_queue(client) -> int: nq1 = process1.nq nq2 = process2.nq if nq1 < nq2: return 0 if nq1 > nq2: return 1 return randint(0, 1) # Link stations source.set_next(decide) decide.set_condition(shortest_queue) decide.add_next(process1) decide.add_next(process2) process1.set_next(dispose) process2.set_next(dispose) # Run simulation simulator.run() # Results name = "2 queues, shortest" enq = process1.statistic_queue_length.mean + process2.statistic_queue_length.mean en = process1.statistic_wip.mean + process2.statistic_wip.mean enq_dict[name] = enq en_dict[name] = en print("E[NQ]=", round(enq, 2), sep="") print("E[N]=", round(en, 2), sep="") ``` -------------------------------- ### Importing Dependencies Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple2.ipynb Imports necessary libraries for numerical processing, optimization, and queue simulation. ```python # Processing results arrays import numpy as np # Optimizer import pybobyqa # Simulator from queuesim.models import mmc_model, get_simulator_from_model ``` -------------------------------- ### queuesim.stations.Source Source: https://github.com/a-herzog/queuesim/blob/master/README.md Represents the entry point for clients into the queueing system. ```APIDOC ## queuesim.stations.Source ### Description Creates a source station where clients enter the system. ### Constructor `queuesim.stations.Source(simulator, count, get_i, getIB=None)` ### Parameters - **simulator** (Simulator) - Required - The simulator instance. - **count** (int) - Required - Number of arrivals to simulate. - **get_i** (str/lambda) - Required - Expression to generate inter-arrival times. - **getIB** (optional) - Optional - Variable arrival batch sizes. ``` -------------------------------- ### Initialize the Simulator Source: https://github.com/a-herzog/queuesim/blob/master/README_simulation.md The Simulator object acts as the central event manager and must be instantiated before creating stations. ```python import queuesim simulator = queuesim.Simulator() ``` -------------------------------- ### Displaying Results Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple2.ipynb Prints the full solution object and the rounded optimal number of operators. ```python print(soln) ``` ```python print("Cost-optimal number of operators:",round(soln.x[0])) ``` -------------------------------- ### Running and evaluating simulations Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities1.ipynb Executes the simulation model with a specific priority function and prints the resulting service, residence, and waiting time statistics. ```python def run_simulation(mean_i, mean_s, c, count, priority, priority_name): # Build model model = mmc_model_priorities(mean_i, mean_s, c, count, priority) # Run simulation simulator = get_simulator_from_model(model) %time simulator.run() # Show results print(priority_name) dispose = model['Dispose'] print(" Service times (S): " + dispose.statistic_client_service.info) print(" Residence times (V): " + dispose.statistic_client_residence.info) print(" Waiting times (W): " + dispose.statistic_client_waiting.info) print() run_simulation(mean_i, mean_s, c, count, priority_FIFO, "FIFO") run_simulation(mean_i, mean_s, c, count, priority_random, "Random") run_simulation(mean_i, mean_s, c, count, priority_LIFO, "LIFO") ``` -------------------------------- ### Import Simulation Modules Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities2.ipynb Imports necessary classes for simulation, graph building, and visualization. ```python # Simulation from queuesim.random_dist import exp as dist_exp from queuesim.descore import Simulator from queuesim.stations import Source, Process, DecideClientType, Dispose # Plot model from queuesim import build_graph import networkx as nx import matplotlib.pyplot as plt ``` -------------------------------- ### Configuring Simulation Parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_course.ipynb Sets the mean inter-arrival time, mean service time, number of operators, and total arrival count for the simulation. ```python # Mean inter-arrival time mean_i = 100 # Mean service time mean_s = 800 # Number of operators c = 10 # Number of arrivals to be simulated count = 500 ``` -------------------------------- ### Define Simulation Parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center_series.ipynb Sets up the variables for the call center simulation including arrival rates, service times, and retry logic. ```python # Mean inter-arrival time mean_i = 100 # Mean service time mean_s_range = range(60, 121, 2) # Mean waiting time tolerance range mean_wt = 300 # Retry retry_probability = 0.2 mean_retry_delay = 600 # Number of operators c = 1 # Number of arrivals to be simulated count = 100_000 ``` -------------------------------- ### Identifying Optimal Configuration Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple1.ipynb Prints the cost-optimal number of operators found within the analyzed range. ```python print("Cost-optimal number of operators:", c_range[np.argmin(costs)]) print("Analyzed range:", c_range[0], "...", c_range[-1]) ``` -------------------------------- ### queuesim.Simulator.run() Source: https://github.com/a-herzog/queuesim/blob/master/README.md The run method executes the simulation event management. ```APIDOC ## queuesim.Simulator.run() ### Description Executes the simulation based on the defined stations and network configuration. ### Method Method call on `queuesim.Simulator` instance. ### Parameters None. ``` -------------------------------- ### Run Simulation in Main vs Background Process Source: https://github.com/a-herzog/queuesim/blob/master/README.md Compare running a simulation directly in the main process versus using a background process for parallel execution. ```python model = ... simulator = queuesim.models.get_simulator_from_model(model) simulator.run() ``` ```python import queuesim.SimProcess model = ... task = SimProcess(model) task.start() model_with_statistic_results = task.results # Accessing the "results" property will wait for simulation finished ``` -------------------------------- ### Setting Model Parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_simple2.ipynb Defines simulation constants including arrival/service processes and associated costs. ```python # Arrivals to be simulated count = 10_000 # Arrival process mean_I = 50 # Service process mean_S = 600 # Costs cost_waiting = 10 # Costs per waiting second cost_c = 120 # Costs per operator ``` -------------------------------- ### Simulate single station with fast operator Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Configures a simulation using a faster processing time parameter for the service station. ```python # Simulator simulator = Simulator() # Stations source = Source(simulator, count, inter_arrival_time) process = Process(simulator, process_time_fast, c) dispose = Dispose(simulator) # Link stations source.set_next(process) process.set_next(dispose) # Run simulation simulator.run() # Results name = "1 queue, fast operator" enq = process.statistic_queue_length.mean en = process.statistic_wip.mean enq_dict[name] = enq en_dict[name] = en print("E[NQ]=", round(enq, 2), sep="") print("E[N]=", round(en, 2), sep="") ``` -------------------------------- ### Define Simulation Parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_complex1.ipynb Sets the arrival count, service time, and cost constants used for revenue calculations. ```python # Arrivals to be simulated count = 100_000 # Service process mean_S = 80 c = 1 # Costs profit_per_client = 100 # Revenue per customer served cost_waiting = 0.02 # Costs per waiting second operation_cost_per_second = 0.5 ``` -------------------------------- ### Initialize Erlang B plotting environment Source: https://github.com/a-herzog/queuesim/blob/master/example_analytic_erlang_b.ipynb Imports necessary modules and configures the matplotlib plotting style for Erlang B analysis. ```python # Erlang module from queuesim.analytic import erlang_b_table # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Defining general plot style plt.style.use('seaborn-v0_8') percent_formater = formater.PercentFormatter(xmax=1, decimals=0) ``` -------------------------------- ### Visualizing Client Counts Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_course.ipynb Extracts WIP statistics from the model and plots the number of clients over time. ```python # Prepare values wip = model['Process'].statistic_wip times, values = wip.values # Plot _, ax = plt.subplots(figsize=(16, 9)) ax.plot(times, values) ax.set_title("Course of the number of clients in the system") ax.set_xlabel("Time") ax.set_ylabel("Number of clients in the system E[N]") ``` -------------------------------- ### Calculate Financial Metrics Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_complex1.ipynb Computes utilization, waiting times, and daily revenue based on the simulation results. ```python # Utilization of the operators rho = np.array([model['meanS'] / model['meanI'] / model['c'] for model in models]) # Mean waiting times waiting_times = np.array([model['Dispose'].statistic_client_waiting.mean for model in models]) # Served client per day clients_per_day = np.array([model['Source'].count / model['Process'].statistic_wip.time * 86400 for model in models]) # Revenue per client yield_per_client = profit_per_client - waiting_times * cost_waiting # Revenue per day yield_per_day = clients_per_day * yield_per_client - operation_cost_per_second * 86400 ``` -------------------------------- ### Defining a Model Dictionary Source: https://github.com/a-herzog/queuesim/blob/master/README_statistics.md Structure a dictionary containing Source, Process, and Dispose station references. ```python model={'Source': source, 'Process': process, 'Dispose': dispose} ``` -------------------------------- ### Importing dependencies Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_GGc.ipynb Imports necessary libraries for numerical operations and analytical validation. ```python # Generating multiple pseudo random numbers as an array and fast array processing import numpy as np # Comparison with analytical results from queuesim.analytic import erlang_c ``` -------------------------------- ### Create model using helper function Source: https://github.com/a-herzog/queuesim/blob/master/README_impatience.md Utilizes the impatience_and_retry_model_build helper function to simplify the creation of models with impatience and retry parameters. ```python model = impatience_and_retry_model_build(mean_i, mean_s, mean_wt, retry_probability, mean_retry_delay, c, count) simulator = get_simulator_from_model(model) simulator.run() ``` -------------------------------- ### Implementing priority functions Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities1.ipynb Defines functions to determine client service order based on waiting time, enabling FIFO, LIFO, or random selection. ```python def priority_FIFO(client, waiting_time): return waiting_time def priority_LIFO(client, waiting_time): return -waiting_time def priority_random(client, waiting_time): return random_float() * 100 ``` -------------------------------- ### Configure LIFO service mode Source: https://github.com/a-herzog/queuesim/blob/master/README_discipline.md Set the LIFO parameter to True in the Process constructor to change the service order from FIFO to LIFO. ```python import queuesim from queuesim.stations import Process, ... from queuesim.random_dist import exp as exp_dist process = Process(simulator, exp_dist(80), c = 1, LIFO = True) ``` -------------------------------- ### Route clients based on shortest queue Source: https://github.com/a-herzog/queuesim/blob/master/README.md Uses a DecideCondition station to dynamically route clients to the process station with the shortest current queue length. ```python source = Source(simulator, count, inter_arrival_time) decide = DecideCondition(simulator) process1 = Process(simulator, service_time1, c1) process2 = Process(simulator, service_time2, c2) dispose = Dispose(simulator) def shortest_queue(client) -> int: nq1 = process1.nq nq2 = process2.nq if nq1 < nq2: return 0 if nq1 > nq2: return 1 return randint(0, 1) source.set_next(decide) decide.set_condition(shortest_queue) decide.add_next(process1) decide.add_next(process2) process1.set_next(dispose) process2.set_next(dispose) ``` -------------------------------- ### Use convenience M/M/c model function Source: https://github.com/a-herzog/queuesim/blob/master/README.md Generates an M/M/c model using the built-in convenience method to simplify station configuration. ```python import queuesim.models model = queuesim.models.mmc_model(100, 80, 1, 100_000) # Parameters: E[I], E[S], c and number of arrivals simulator = queuesim.models.get_simulator_from_model(model) simulator.run() ``` -------------------------------- ### Visualize Performance Metrics Source: https://github.com/a-herzog/queuesim/blob/master/example_analytic_erlang_c_ext.ipynb Generate a dual-axis plot showing waiting time, cancellation probability, blocking probability, and real utilization. ```python _, ax = plt.subplots(figsize=(16, 9)) line1 = ax.plot(results["rho_offered"], results["E[W]"], 'b', label="E[W]") ax.tick_params(axis='y', labelcolor='b') ax.set_xlabel("Offered utilization") ax.set_ylabel("E[W]", color='b') ax.xaxis.set_major_formatter(percent_formater) lines1, labels1 = ax.get_legend_handles_labels() ax = ax.twinx() line2 = ax.plot(results["rho_offered"], results["P(A)"], 'r', label="P(A) (waiting cancellations)") line3 = ax.plot(results["rho_offered"], results["P(blocked)"], 'r--', label="P(blocked) (blocked clients)") line4 = ax.plot(results["rho_offered"], results["rho_real"], 'g', label="$\rho$ (real utilization)") ax.set_ylabel("P(A) and $\rho$") ax.yaxis.set_major_formatter(percent_formater) lines2, labels2 = ax.get_legend_handles_labels() ax.set_title("Extended Erlang C model at different utilizations") ax.legend(lines1 + lines2, labels1 + labels2) ``` -------------------------------- ### Visualizing waiting time distribution Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_simple.ipynb Compares the simulated waiting time frequency distribution against the theoretical Erlang C probability density. ```python # Get frequency distribution of the waiting times stat = model['Dispose'].statistic_client_waiting # Build histogram values hist_y_sum = sum(stat.histogram) hist_y = stat.histogram hist_x = [i * stat.histogram_stepwide for i in range(len(hist_y))] # Build P(W=t) by Erlang C formula erlang_hist_x = range(0, len(stat.histogram) * stat.histogram_stepwide, stat.histogram_stepwide) erlang_hist_y = [] last = 0 for t in erlang_hist_x: value = analytic.Pt(t) erlang_hist_y.append(value - last) last = value # Show histogram _, ax = plt.subplots(figsize=(16, 9)) ax.bar(hist_x, hist_y, width=stat.histogram_stepwide * 0.75) ax.set_ylim(0, max(hist_y[1:])) ax.yaxis.set_major_formatter(formater.PercentFormatter(xmax=hist_y_sum, decimals=1)) ax.tick_params(axis='y', labelcolor='b') ax.set_ylabel("Probability from simulation", color='b') ax.set_xlabel("Waiting time") ax = ax.twinx() ax.plot(erlang_hist_x, erlang_hist_y, 'r', linewidth=2) ax.set_ylim(0, hist_y[1] / hist_y_sum) ax.yaxis.set_major_formatter(formater.PercentFormatter(xmax=1, decimals=1)) ax.tick_params(axis='y', labelcolor='r') ax.set_ylabel("Probability from Erlang C", color='r') ax.set_title("Frequency distribution of the waiting times of the clients") ``` -------------------------------- ### Simulate a single station with parallel operators Source: https://github.com/a-herzog/queuesim/blob/master/exmaple_sim_shortest_queue.ipynb Configures a simulation with a single service station utilizing two parallel operators to handle incoming traffic. ```python # Simulator simulator = Simulator() # Stations source = Source(simulator, count, inter_arrival_time) process = Process(simulator, process_time, 2 * c) dispose = Dispose(simulator) # Link stations source.set_next(process) process.set_next(dispose) # Run simulation simulator.run() # Results name = "1 queue, 2 parallel operators" enq = process.statistic_queue_length.mean en = process.statistic_wip.mean enq_dict[name] = enq en_dict[name] = en print("E[NQ]=", round(enq, 2), sep="") print("E[N]=", round(en, 2), sep="") ``` -------------------------------- ### Defining simulation parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_GGc.ipynb Sets the mean inter-arrival time, mean service time, number of operators, and total arrival count. ```python # Means inter-arrival time mean_i = 100 # Means service time mean_s = 240 # Number of operators c = 3 # Number of arrivals to be simulated count = 1_000_000 ``` -------------------------------- ### Executing the M/M/1 simulation loop Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_MM1.ipynb Calculates waiting times by iterating through arrival and service times. This loop can be adapted for G/G/1 models by changing the random number generator. ```python waiting_sum = server_free_at = 0 for (time, s) in zip(np.cumsum(np.random.exponential(mean_i, count)), np.random.exponential(mean_s, count)): waiting_sum += max(0, server_free_at - time) server_free_at = max(server_free_at, time) + s ``` -------------------------------- ### Defining simulation parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities1.ipynb Sets the base variables for the M/M/c simulation including arrival rates, service times, and sample size. ```python # Mean inter-arrival time mean_i = 100 # Mean service time mean_s = 80 # Number of operators c = 1 # Number of arrivals to be simulated count = 500_000 ``` -------------------------------- ### Printing optimization results Source: https://github.com/a-herzog/queuesim/blob/master/example_optimize_complex2.ipynb Displays the full solution object containing the optimal parameters and objective value. ```python print(soln) ``` -------------------------------- ### Implement retry logic for canceled clients Source: https://github.com/a-herzog/queuesim/blob/master/README_impatience.md Uses a Decide station to route a percentage of canceled clients back to the process station for a retry. ```python simulator = queuesim.Simulator() source = Source(simulator, count, get_i) process = Process(simulator, get_s, c, getNu=getNu) decide = Decide() dispose = Dispose(simulator) source.set_next(process) process.set_next(dispose) process.set_next_cancel(decide) decide.add_next(process, 0.4) # 40% will retry decide.add_next(dispose, 1 - 0.6) ``` -------------------------------- ### Implement decide by chance Source: https://github.com/a-herzog/queuesim/blob/master/README_control.md Distributes clients to process stations based on normalized rates, resulting in probabilistic routing. ```python from queuesim.stations import Decide decide = Decide(simulator) decide.add_next(process1, 1) decide.add_next(process2, 1) ``` -------------------------------- ### Visualizing the model graph Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_call_center.ipynb Generating a network graph to visualize the station connections. ```python dg = build_graph([source]) _, ax = plt.subplots(figsize=(19, 9)) nx.draw(dg, ax=ax, with_labels=True, node_color='#CCCCFF', node_size=2000, arrowsize=30, width=2) ``` -------------------------------- ### Run Simulation and Display Results Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_mmc_priorities2.ipynb Executes the simulation and prints statistical results for each client type. ```python # Run simulation %time simulator.run() # Show results print("ClientsA") print(" Service times (S): " + dispose1.statistic_client_service.info) print(" Residence times (V): " + dispose1.statistic_client_residence.info) print(" Waiting times (W): " + dispose1.statistic_client_waiting.info) print("ClientsB") print(" Service times (S): " + dispose2.statistic_client_service.info) print(" Residence times (V): " + dispose2.statistic_client_residence.info) print(" Waiting times (W): " + dispose2.statistic_client_waiting.info) ``` -------------------------------- ### Importing dependencies and configuring plot style Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_MM1.ipynb Initializes NumPy for random number generation, imports analytical functions, and sets the Matplotlib plotting style. ```python # Generating multiple pseudo random numbers as an array import numpy as np # Comparison with analytical results from queuesim.analytic import erlang_c # Plotting modules import matplotlib.pyplot as plt import matplotlib.ticker as formater # Defining general plot style plt.style.use('seaborn-v0_8') ``` -------------------------------- ### Visualize a queueing network Source: https://github.com/a-herzog/queuesim/blob/master/README_networks.md Generates a digraph using build_graph and plots it with networkx and matplotlib. ```python from queuesim import Simulator from queuesim.stations import Source, ... from queuesim import build_graph import matplotlib.pyplot as plt import networkx as nx simulator = Simulator() simulator = Simulator() source = Source(simulator, ...) dg = build_graph([source]) fig, ax = plt.subplots(figsize=(19, 9)) nx.draw(dg, ax=ax, with_labels=True, node_color='#CCCCFF', node_size=2000, arrowsize=30, width=2) ``` -------------------------------- ### Define client-specific service times at a Process station Source: https://github.com/a-herzog/queuesim/blob/master/README_clienttypes.md Use the getS_client_type dictionary to provide specific service time distributions for different client types. ```python import queuesim from queuesim.random_dist import exp as exp_dist from queuesim.stations import Process, ... simulator = queuesim.Simulator() process = Process(simulator, exp_dist(100), c=3, getS_client_type = {"Clients A": exp_dist(120)}) ``` -------------------------------- ### queuesim.stations.Process Source: https://github.com/a-herzog/queuesim/blob/master/README.md Represents a service station with a queue and service desk. ```APIDOC ## queuesim.stations.Process ### Description Creates a process station where clients are served. ### Constructor `queuesim.stations.Process(simulator, get_s, c, **kwargs)` ### Parameters - **simulator** (Simulator) - Required - The simulator instance. - **get_s** (str/lambda) - Required - Expression to generate service times. - **c** (int) - Required - Number of parallel operators. - **kwargs** (optional) - Optional - Includes parameters like getNu, getS2, K, b, LIFO, getPriority, record_values, getS_client_type, getNu_client_type. ``` -------------------------------- ### Route clients using DecideClientType Source: https://github.com/a-herzog/queuesim/blob/master/README_clienttypes.md Configure routing logic based on client type names using set_next and set_next_default methods. ```python import queuesim from queuesim.stations import DecideClientType, Dispose, ... simulator = queuesim.Simulator() decide = DecideClientType(simulator) dispose1 = Dispose(simulator) dispose2 = Dispose(simulator) decide.set_next("Clients A", dispose1) decide.set_next_default(dispose2) ``` -------------------------------- ### erlang_c_ext Source: https://github.com/a-herzog/queuesim/blob/master/README_analytical.md Calculates values for the extended Erlang-C formula, accounting for client impatience and limited system size. ```APIDOC ## erlang_c_ext(l, mu, nu, c, K) ### Description Calculates extended Erlang-C metrics including offered/real utilization, blocking probability, cancellation percentage, and various average system metrics. ### Parameters - **l** (float) - Arrival rate (lambda) - **mu** (float) - Service rate (mu) - **nu** (float) - Cancellation rate (nu) - **c** (int) - Number of operators - **K** (int) - Maximum number of clients in system ### Returns - **Object** - Contains attributes: rho_offered, rho_real, p_blocked, PA, ENQ, EN, EW, EV. ``` -------------------------------- ### Implement decide by shortest queue Source: https://github.com/a-herzog/queuesim/blob/master/README_control.md Uses a custom condition function to route clients to the station with the shortest current queue length. ```python from random import randint from queuesim.stations import DecideCondition decide = DecideCondition(simulator) def shortest_queue(client) -> int: nq1 = process1.nq nq2 = process2.nq if nq1 < nq2: return 0 if nq1 > nq2: return 1 return randint(0, 1) decide.set_condition(shortest_queue) decide.add_next(process1) decide.add_next(process2) ``` -------------------------------- ### Generating arrival and service times Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_GGc.ipynb Creates arrays for absolute arrival times and service durations using exponential distributions. ```python arrival_times = np.cumsum(np.random.exponential(mean_i, count)) # Absolute arrival times, not inter-arrival times service_times = np.random.exponential(mean_s, count) ``` -------------------------------- ### Defining simulation parameters Source: https://github.com/a-herzog/queuesim/blob/master/example_sim_minimal_MM1.ipynb Sets the mean inter-arrival time, mean service time, and the total number of arrivals for the simulation. ```python # Means inter-arrival time mean_i = 100 # Means service time mean_s = 80 # Number of arrivals to be simulated count = 5_000_000 ``` -------------------------------- ### Connect simulation stations Source: https://github.com/a-herzog/queuesim/blob/master/README_simulation.md Define the flow of clients between stations using the set_next method. ```python source.set_next(process) process.set_next(dispose) ```