Core Modules

Networks, nodes, classes, distributions, solvers.

These modules provide the fundamental building blocks for creating and solving queueing models.

Network Models (line_solver.lang)

The lang module contains the core classes for building queueing network models.

Main Classes

class Network(name='LineNetwork')[source]

Bases: Network, Element

Queueing network model for LINE.

The Network class represents a complete queueing network model with nodes, job classes, and routing. It compiles to a NetworkStruct for solver consumption.

Initialize a network.

Parameters:

name (str) – Network name (default: “LineNetwork”)

__init__(name='LineNetwork')[source]

Initialize a network.

Parameters:

name (str) – Network name (default: “LineNetwork”)

add_node(node)[source]

Add a node to the network.

Parameters:

node (Node) – Node to add (Queue, Source, Sink, Delay, Fork, Join, etc.)

Raises:

ValueError – If node already in network (when allow_replace is False)

add_class(jobclass)[source]

Add a job class to the network.

Parameters:

jobclass (JobClass) – Job class to add (OpenClass or ClosedClass)

Raises:

ValueError – If class already in network

addClass(jobclass)[source]

MATLAB-compatible alias for add_class().

Add a link between two nodes.

Parameters:
  • source (Node) – Source node

  • dest (Node) – Destination node

Raises:

ValueError – If nodes not in network

Add multiple links via routing matrix.

Parameters:

routing_matrix (RoutingMatrix | numpy.ndarray) – RoutingMatrix or numpy array with probabilities

Create serial links between nodes.

Parameters:

nodes (Node) – Variable number of nodes to link in sequence

add_region(name_or_node, *nodes)[source]

Add a finite capacity region containing the specified nodes.

A finite capacity region constrains the total number of jobs that can be present in a group of nodes simultaneously.

Parameters:
  • name_or_node (str | Node) – Either a name for the region (str) or the first node. If a string is provided, it’s used as the region name. If a node is provided, an auto-generated name is used.

  • *nodes (Node) – Additional nodes to include in the region

Returns:

The created Region object for further configuration

Return type:

Region

Examples

# With auto-generated name (FCR1, FCR2, etc.) fcr = model.add_region(queue1) fcr = model.add_region(queue1, queue2)

# With custom name fcr = model.add_region(‘MyRegion’, queue1) fcr = model.add_region(‘MyRegion’, queue1, queue2)

addRegion(name_or_node, *nodes)[source]

MATLAB-compatible alias for add_region().

property regions: List[Region]

Get the list of finite capacity regions.

get_regions()[source]

Get the list of finite capacity regions.

getRegions()[source]

MATLAB-compatible alias for get_regions().

init_routing_matrix()[source]

Initialize an empty routing matrix for all nodes and classes.

Returns:

RoutingMatrix with zeros (no routing initially)

Return type:

RoutingMatrix

set_checks(val)[source]

Enable or disable link-time model checks (e.g. the OI permutation- invariance check). Mirrors MATLAB model.setChecks.

setChecks(val)

Enable or disable link-time model checks (e.g. the OI permutation- invariance check). Mirrors MATLAB model.setChecks.

Set the routing matrix for the network.

Parameters:

routing_matrix – RoutingMatrix, dict with (from_class, to_class) keys, or 2D list/array (applies same routing to all classes)

Raises:

ValueError – If routing matrix dimensions don’t match network, if any routing probability is negative, or if a node’s outgoing total in some class exceeds 1.

is_routing_ergodic(P=None)[source]

Check if the queueing network routing matrix is ergodic (irreducible).

This checks only the routing structure, not the full CTMC state space. A routing is ergodic if all stations communicate, meaning the routing matrix does not create absorbing states or disconnected components.

Parameters:

P – Optional routing matrix (list of lists). If not provided, it will be retrieved via get_linked_routing_matrix().

Returns:

  • absorbingStations: list of station names that are absorbing

  • transientStations: list of station names that are transient

  • numSCCs: number of strongly connected components

  • isReducible: True if the routing creates a reducible structure

Return type:

Tuple of (is_ergodic, info) where info is a dict containing

get_routing_matrix()[source]

Get the current routing matrix.

Returns:

RoutingMatrix or None if not set

Return type:

RoutingMatrix | None

get_linked_routing_matrix()[source]

Get the linked routing matrix (rtorig from NetworkStruct).

This returns the original routing matrix in the format used by the compiled NetworkStruct. The matrix is structured as a list of lists: P[r][s] is the routing matrix from class r to class s.

Returns:

List of routing matrices, or None if not available

reset_network(hard=True)[source]

Reset the network configuration.

This clears the routing matrix and struct, allowing the network to be reconfigured. Used by model transformations.

Parameters:

hard (bool) – If True, also clears the routing matrix

get_log_path()[source]

Get the path for logger output files.

Returns:

Path for log files, or temp directory if not set

Return type:

str

set_log_path(path)[source]

Set the path for logger output files.

Parameters:

path (str) – Directory path for log files

getLogPath()

Get the path for logger output files.

Returns:

Path for log files, or temp directory if not set

Return type:

str

setLogPath(path)

Set the path for logger output files.

Parameters:

path (str) – Directory path for log files

Link the network with logging enabled for specified nodes.

This method modifies the network by inserting Logger nodes before and after the logged nodes to capture arrival and departure timestamps.

Ported from MATLAB’s MNetwork.linkAndLog.

Parameters:
  • P – Routing matrix (dict of dicts of numpy arrays)

  • is_node_logged (list) – Boolean list indicating which nodes should be logged

  • log_path (str) – Path for log files (optional, uses model’s log path if not set)

Returns:

Tuple of (loggerBefore, loggerAfter) - lists of Logger nodes created

linkAndLog(P, is_node_logged, log_path=None)

Link the network with logging enabled for specified nodes.

This method modifies the network by inserting Logger nodes before and after the logged nodes to capture arrival and departure timestamps.

Ported from MATLAB’s MNetwork.linkAndLog.

Parameters:
  • P – Routing matrix (dict of dicts of numpy arrays)

  • is_node_logged (list) – Boolean list indicating which nodes should be logged

  • log_path (str) – Path for log files (optional, uses model’s log path if not set)

Returns:

Tuple of (loggerBefore, loggerAfter) - lists of Logger nodes created

get_connection_matrix()[source]

Get the network connection (adjacency) matrix.

Returns:

(N x N) binary matrix where 1 indicates a connection

Return type:

numpy.ndarray

nodes()[source]

Get list of all nodes (method alias for compatibility).

get_stations()[source]

Get list of all station nodes.

property classes: List[JobClass]

Get list of all job classes (property for compatibility with MATLAB API).

get_class_names()[source]

Return the list of job-class names, indexed by class.

References

MATLAB: matlab/src/lang/@MNetwork/getClassNames.m

get_node_names()[source]

Return the list of node names, indexed by node.

References

MATLAB: matlab/src/lang/@MNetwork/getNodeNames.m

get_station_names()[source]

Return the list of station names, indexed by station.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (getStationNames)

get_class_switching_mask()[source]

Return the class-switching mask, a boolean matrix whose entry (r, s) is true only if jobs in class r can switch into class s at some node in the network.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (getClassSwitchingMask)

has_product_form_solution()[source]

Return whether the model admits a product-form solution.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (hasProductFormSolution)

get_node_by_name(name)[source]

Get node by name.

Parameters:

name (str) – Node name

Returns:

Node or None if not found

Return type:

Node | None

get_station_by_name(name)[source]

Get station by name.

Parameters:

name (str) – Station name

Returns:

Station or None if not found

Return type:

Station | None

get_class_by_name(name)[source]

Get job class by name.

Parameters:

name (str) – Class name

Returns:

JobClass or None if not found

Return type:

JobClass | None

get_class_index(jobclass)[source]

Get 1-based index of a job class.

Parameters:

jobclass (JobClass | str) – JobClass instance or class name

Returns:

1-based class index

Return type:

int

get_source()[source]

Get Source node (if present).

get_sink()[source]

Get Sink node (if present).

get_index_source_node()[source]

Get the index of the Source node (-1 if not present).

get_index_sink_node()[source]

Get the index of the Sink node (-1 if not present).

has_open_classes()[source]

Check if network has any open classes.

has_closed_classes()[source]

Check if network has any closed classes.

has_fork()[source]

Check if network has any fork nodes.

has_join()[source]

Check if network has any join nodes.

init_used_features()[source]

Initialize the used features set.

set_used_lang_feature(feature)[source]

Set a feature as used in this model.

get_used_lang_features()[source]

Get the features used by this model.

Returns:

The set of features used by this model.

Return type:

SolverFeatureSet

initUsedFeatures()

Initialize the used features set.

setUsedLangFeature(feature)

Set a feature as used in this model.

getUsedLangFeatures()

Get the features used by this model.

Returns:

The set of features used by this model.

Return type:

SolverFeatureSet

refresh_struct()[source]

Compile model to NetworkStruct for solver consumption.

Always performs a full rebuild of the struct from scratch.

refresh_rates()[source]

Refresh only the service/arrival rates in the cached NetworkStruct.

This is a lightweight alternative to refresh_struct() when only service times have changed (e.g., during iterative solver updates). It updates rates, scv, proc, and procid without recomputing routing, visits, or other structural data.

If no cached struct exists, falls back to full refresh_struct().

refreshRates()

Refresh only the service/arrival rates in the cached NetworkStruct.

This is a lightweight alternative to refresh_struct() when only service times have changed (e.g., during iterative solver updates). It updates rates, scv, proc, and procid without recomputing routing, visits, or other structural data.

If no cached struct exists, falls back to full refresh_struct().

getStateSpace(*args)[source]

Get the CTMC state space of the model.

Delegates to SolverCTMC; results are not cached. For repeated use, build a SolverCTMC(model, …) and call getStateSpace(…) on it.

Returns:

(stateSpace, nodeStateSpace)

get_state_space(*args)[source]

Get the CTMC state space (snake_case alias for getStateSpace).

stateSpace(*args)[source]

Get the CTMC state space (alias for getStateSpace).

reset_struct()[source]

Reset struct compilation flag.

reset()[source]

Reset the network to allow re-configuration.

This resets the routing matrix and struct, allowing nodes to be reconfigured (e.g., changing routing strategies) before re-solving. Also clears solver results from cache nodes to prevent stale hit/miss probabilities from affecting subsequent solver runs.

struct()[source]

Get compiled NetworkStruct (alias for get_struct).

Returns:

NetworkStruct for solver use

Return type:

NetworkStruct

print_routing_matrix(onlyclass=None)[source]

Print the routing matrix of the network.

Displays routing probabilities between nodes and classes in a human-readable format, including class-switching routes.

Parameters:

onlyclass – Optional filter for a specific class

References

MATLAB: MNetwork.printRoutingMatrix Java: Network.printRoutingMatrix

Re-link the network with a new routing matrix.

This is similar to link() but resets the struct first to allow iterative optimization of routing parameters.

Parameters:

routing_matrix (RoutingMatrix) – New RoutingMatrix specifying routing probabilities

set_reward(name, reward_fn)[source]

Add a reward function to the network.

Parameters:
  • name (str) – Reward name

  • reward_fn – Callable that takes RewardState and returns value

get_reward(name)[source]

Get reward function by name.

get_rewards()[source]

Get all rewards.

init_default()[source]

Initialize network with default state.

For closed classes, all jobs start at their reference station. For open classes, sources start with potential arrivals.

Delegates to initFromMarginal to generate proper per-node state spaces and state priors, which are needed for CTMC transient analysis.

has_init_state()[source]

Check if network has initialized state.

Mirrors MATLAB MNetwork.hasInitState: the model counts as initialized only when EVERY stateful node carries a state, so a partially initialized model still triggers init_default.

set_state(state)[source]

Set state for nodes.

Parameters:

state (Dict[str, numpy.ndarray]) – Dict mapping node names to state vectors

state()[source]

Get current state of all stateful nodes (alias for get_state).

Returns:

Dict mapping node names to state vectors

Return type:

Dict[str, numpy.ndarray]

get_state_marginal()[source]

Get the stored marginal state used for CTMC initial state matching.

Returns:

Flat array of marginal job counts [n[0,0], n[0,1], …, n[M-1,K-1]] where n[i,k] is number of jobs of class k at station i. Returns None if no marginal has been set.

Return type:

numpy.ndarray

getStateMarginal()

Get the stored marginal state used for CTMC initial state matching.

Returns:

Flat array of marginal job counts [n[0,0], n[0,1], …, n[M-1,K-1]] where n[i,k] is number of jobs of class k at station i. Returns None if no marginal has been set.

Return type:

numpy.ndarray

init_from_marginal_and_started(n, s)[source]

Initialize network state from marginal queue lengths and started jobs.

This method generates the full state space for each station based on the marginal job counts, sets the state prior (first state with probability 1 by default), and sets the current state.

Parameters:
  • n – Marginal queue lengths matrix (nstations x nclasses). n[i][r] is the number of jobs of class r at station i.

  • s – Started jobs matrix (nstations x nclasses). s[i][r] is the number of jobs of class r in service at station i.

init_from_marginal(n)[source]

Initialize network state from marginal queue lengths only.

This is equivalent to calling init_from_marginal_and_started with a zero matrix for started jobs.

Parameters:

n – Marginal queue lengths. Can be: - 1D list/array with one value per station (single class) - 2D list/array (nstations x nclasses)

to_java()[source]

Convert Network for JVM interoperability.

Not available in the native Python implementation. The native Python solver operates independently of the JVM. For JVM interoperability call the canonical JAR (common/jline.jar) directly.

copy()[source]

Create a deep copy of the network.

This method creates a new Network instance with copies of all nodes, classes, and routing. The copied network is independent of the original and can be modified without affecting the original.

This is required for model transformations like Heidelberger-Trivedi (H-T) for fork-join networks.

Returns:

A deep copy of this network

Return type:

Network

Example

>>> model = Network('Original')
>>> # ... build model ...
>>> model_copy = model.copy()
>>> # Modify model_copy without affecting model
getRoutingMatrix()

Get the current routing matrix.

Returns:

RoutingMatrix or None if not set

Return type:

RoutingMatrix | None

getStations()

Get list of all station nodes.

getNodeByName(name)

Get node by name.

Parameters:

name (str) – Node name

Returns:

Node or None if not found

Return type:

Node | None

getSource()

Get Source node (if present).

getSink()

Get Sink node (if present).

getClassNames()

Return the list of job-class names, indexed by class.

References

MATLAB: matlab/src/lang/@MNetwork/getClassNames.m

getNodeNames()

Return the list of node names, indexed by node.

References

MATLAB: matlab/src/lang/@MNetwork/getNodeNames.m

getStationNames()

Return the list of station names, indexed by station.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (getStationNames)

getClassSwitchingMask()

Return the class-switching mask, a boolean matrix whose entry (r, s) is true only if jobs in class r can switch into class s at some node in the network.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (getClassSwitchingMask)

hasProductFormSolution()

Return whether the model admits a product-form solution.

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (hasProductFormSolution)

resetStruct()

Reset struct compilation flag.

setReward(name, reward_fn)

Add a reward function to the network.

Parameters:
  • name (str) – Reward name

  • reward_fn – Callable that takes RewardState and returns value

getReward(name)

Get reward function by name.

getRewards()

Get all rewards.

version()

Get the LINE solver version string.

print_struct()[source]

Print a summary of the compiled NetworkStruct (wrapper-compatible).

chain_index(jobclass)

Get the 1-based index of the chain containing a class (object or name).

stateful_index(node)

Get the 1-based index of a node among the stateful nodes (-1 if not stateful).

plot(graph_type='station', method='names', **kwargs)[source]

Plot the network as a directed graph (see lang/viz.py).

static serial_routing(*args)[source]

Create a routing probability matrix for serial (tandem) routing through nodes.

Jobs flow from each node to the next in the provided order. For closed networks (last node is not a Sink), the last node automatically routes back to the first node to form a cycle.

If a node appears multiple times in the sequence (e.g., for cyclic routing where the first node is repeated at the end), the duplicate is mapped back to the original node index to create a properly sized routing matrix.

Parameters:

*args – Either a single list of nodes, or nodes passed as separate arguments

Returns:

2D list of routing probabilities, where result[i][j] is the probability of routing from node i to node j. The matrix is sized for all nodes in the model, with indices matching model.get_nodes() order.

static serialRouting(*args)

Create a routing probability matrix for serial (tandem) routing through nodes.

Jobs flow from each node to the next in the provided order. For closed networks (last node is not a Sink), the last node automatically routes back to the first node to form a cycle.

If a node appears multiple times in the sequence (e.g., for cyclic routing where the first node is repeated at the end), the duplicate is mapped back to the original node index to create a properly sized routing matrix.

Parameters:

*args – Either a single list of nodes, or nodes passed as separate arguments

Returns:

2D list of routing probabilities, where result[i][j] is the probability of routing from node i to node j. The matrix is sized for all nodes in the model, with indices matching model.get_nodes() order.

static cyclic(N, D, strategy, S=None)[source]

Create a cyclic queueing network with specified scheduling strategies.

Creates a closed queueing network where jobs cycle through stations in a round-robin fashion (1 -> 2 -> … -> M -> 1).

Parameters:
  • N – Population vector [1 x R] or list - number of jobs per class

  • D – Service demand matrix [M x R] - service demands at each station per class

  • strategy – List of scheduling strategies for each station [M] (e.g., SchedStrategy.FCFS, SchedStrategy.PS, SchedStrategy.INF)

  • S – Number of servers per station [M x 1] or list (default: 1 for each station)

Returns:

Configured closed queueing network

Return type:

Network

Example

>>> N = [10]  # 10 jobs of class 1
>>> D = [[0.5], [1.0]]  # Service demands at 2 stations
>>> strategy = [SchedStrategy.PS, SchedStrategy.FCFS]
>>> model = Network.cyclic(N, D, strategy)

References

MATLAB: matlab/src/lang/JNetwork.m Java: jar/src/main/kotlin/jline/lang/Network.java

jsimg_view()

Open the model in JMT’s JSIMgraph graphical editor.

This method exports the network to JSIMG format (JMT simulation model) and opens it in JSIMgraph for viewing and editing.

Returns:

True if JMT was launched successfully, False otherwise

Raises:

ImportError – If io module is not available

Return type:

bool

Example

>>> model = Network('MyModel')
>>> # ... build model ...
>>> model.jsimgView()  # Opens in JMT graphical editor

References

MATLAB: matlab/src/lang/@MNetwork/jsimgView.m

jsimw_view()

Open the model in JMT’s JSIMwiz wizard interface.

This method exports the network to JSIMG format and opens it in JSIMwiz for wizard-style configuration and simulation.

Returns:

True if JMT was launched successfully, False otherwise

Return type:

bool

Example

>>> model = Network('MyModel')
>>> # ... build model ...
>>> model.jsimwView()  # Opens in JMT wizard

References

MATLAB: matlab/src/lang/@MNetwork/jsimwView.m

view()[source]

Open the model in JMT’s graphical editor (alias for jsimgView).

This is a convenience alias that opens the model in JSIMgraph, providing a visual representation of the queueing network.

Returns:

True if JMT was launched successfully, False otherwise

Return type:

bool

Example

>>> model = Network('MyModel')
>>> # ... build model ...
>>> model.view()  # Opens in JMT graphical editor

References

MATLAB: matlab/src/lang/@MNetwork/view.m

modelView()[source]

Open the model in JSIMgraph viewer.

Exports the network to JSIMG format and launches JMT’s JSIMgraph as a subprocess to display an interactive visualization.

Returns:

True if the viewer was launched successfully, False otherwise

Return type:

bool

References

MATLAB: matlab/src/lang/@MNetwork/modelView.m

model_view()

Open the model in JSIMgraph viewer.

Exports the network to JSIMG format and launches JMT’s JSIMgraph as a subprocess to display an interactive visualization.

Returns:

True if the viewer was launched successfully, False otherwise

Return type:

bool

References

MATLAB: matlab/src/lang/@MNetwork/modelView.m

static tandem(lambda_rates, D, strategies)[source]

Create a tandem network with specified scheduling strategies.

Creates an open queueing network in tandem configuration.

Parameters:
  • lambda_rates (numpy.ndarray) – Array of arrival rates for each class (R,)

  • D (numpy.ndarray) – Service time matrix (M x R), where D[i,r] is mean service time of class r at station i

  • strategies (List) – List of scheduling strategies for each station

Returns:

Configured tandem queueing network

Return type:

Network

References

MATLAB: matlab/src/lang/@MNetwork/tandem.m

static cluster_ps(lambda_rates, D, S=None, dispatching=None)[source]

Open PS cluster (single-server queues unless S overrides multiplicity).

static cluster_fcfs(lambda_rates, D, S=None, dispatching=None)[source]

Open FCFS cluster.

static cluster_closed(N, Z, D, strategies, S=None, dispatching=None)[source]

Create a closed server-farm network: Think -> Dispatcher -> Servers -> Think.

Parameters:
  • N (numpy.ndarray) – Per-class population (1, R) or (R,)

  • Z (numpy.ndarray) – Per-class think times (1, R) or (R,)

  • D (numpy.ndarray) – Service time matrix (M, R)

  • strategies (List) – Per-server scheduling strategies (length M)

  • S (numpy.ndarray | None) – Optional per-server multiplicity (M,)

  • dispatching (RoutingStrategy) – Dispatching policy (defaults to RAND)

static tandem_ps_inf(lambda_rates, D, Z=None)

Create a tandem network with PS queues and INF (delay) stations.

Creates an open queueing network with: - Source node generating arrivals - Optional Delay stations (INF scheduling) from Z - Queue stations (PS scheduling) from D - Sink node

Parameters:
  • lambda_rates (numpy.ndarray) – Array of arrival rates for each class (R,)

  • D (numpy.ndarray) – Service time matrix for queues (M x R), where M is number of PS queues and R is number of classes

  • Z (numpy.ndarray | None) – Optional delay service times (Mz x R), where Mz is number of delay stations

Returns:

Configured tandem queueing network

Return type:

Network

Example

>>> lambda_rates = np.array([0.02, 0.04])
>>> D = np.array([[10, 5], [5, 9]])
>>> Z = np.array([[91, 92]])
>>> model = Network.tandemPsInf(lambda_rates, D, Z)

References

MATLAB: matlab/src/lang/@MNetwork/tandemPsInf.m

static tandem_ps(lambda_rates, D)

Create an open tandem network of PS queues (no delay stations).

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (tandemPs)

static tandem_fcfs(lambda_rates, D)

Create an open tandem network of FCFS queues (no delay stations).

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (tandemFcfs)

static tandem_fcfs_inf(lambda_rates, D, Z=None)

Create an open tandem network with FCFS queues and INF (delay) stations.

Parameters:
  • lambda_rates (numpy.ndarray) – Array of arrival rates for each class (R,)

  • D (numpy.ndarray) – Service time matrix for FCFS queues (M x R)

  • Z (numpy.ndarray | None) – Optional delay service times (Mz x R)

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (tandemFcfsInf)

static cyclic_ps_inf(N, D, Z, S=None)

Create a cyclic network with Delay (INF) stations followed by PS queues.

This creates a closed queueing network where: - The first MZ stations are Delays (infinite server, think time stations) - The remaining M stations are PS (processor sharing) queues

Parameters:
  • N – Population vector [1 x R] or list - number of jobs per class

  • D – Service demand matrix [M x R] - demands at queue stations per class

  • Z – Think time matrix [MZ x R] - think times at delay stations per class If all zeros, no delay stations are created.

  • S – Number of servers per queue station [M x 1] or list (default: 1 each)

Returns:

Configured closed queueing network with delays and PS queues

Return type:

Network

Example

>>> N = [10]  # 10 jobs
>>> D = [[1.0], [0.5]]  # Demands at 2 queues
>>> Z = [[5.0]]  # 5 seconds think time at 1 delay
>>> model = Network.cyclicPsInf(N, D, Z)

References

MATLAB: matlab/src/lang/JNetwork.m Java: jar/src/main/kotlin/jline/lang/Network.java

static cyclic_fcfs(N, D, S=None)

Create a cyclic queueing network with FCFS scheduling at all stations.

Parameters:
  • N – Population vector [1 x R] or list - number of jobs per class

  • D – Service demand matrix [M x R] - service demands at each station per class

  • S – Number of servers per station [M x 1] or list (default: 1 each)

Returns:

Configured closed queueing network with FCFS scheduling

Return type:

Network

Example

>>> N = [10]  # 10 jobs
>>> D = [[0.5], [1.0]]  # Service demands at 2 stations
>>> model = Network.cyclicFcfs(N, D)

References

MATLAB: matlab/src/lang/JNetwork.m Java: jar/src/main/kotlin/jline/lang/Network.java

static cyclic_fcfs_inf(N, D, Z=None, S=None)

Create a cyclic closed network with Delay (INF) stations followed by FCFS queues.

Parameters:
  • N – Population vector [1 x R] or list - number of jobs per class

  • D – Service demand matrix [M x R] - demands at FCFS queues per class

  • Z – Think time matrix [MZ x R] at delay stations per class

  • S – Number of servers per FCFS queue [M x 1] or list (default: 1 each)

References

MATLAB: matlab/src/lang/@MNetwork/MNetwork.m (cyclicFcfsInf)

static cyclic_ps(N, D, S=None)

Create a cyclic queueing network with PS scheduling at all stations.

Parameters:
  • N – Population vector [1 x R] or list - number of jobs per class

  • D – Service demand matrix [M x R] - service demands at each station per class

  • S – Number of servers per station [M x 1] or list (default: 1 each)

Returns:

Configured closed queueing network with PS scheduling

Return type:

Network

Example

>>> N = [10]  # 10 jobs
>>> D = [[0.5], [1.0]]  # Service demands at 2 stations
>>> model = Network.cyclicPs(N, D)

References

MATLAB: matlab/src/lang/JNetwork.m Java: jar/src/main/kotlin/jline/lang/Network.java

static cluster(lambda_rates, D, strategies, S=None, dispatching=None)[source]

Create an open server-farm network: Source -> Dispatcher -> Servers -> Sink.

The dispatcher is a Router that distributes incoming jobs to the M parallel server queues according to the supplied dispatching strategy (RAND, RROBIN, JSQ, …).

Parameters:
  • lambda_rates (numpy.ndarray) – Per-class arrival rates (R,)

  • D (numpy.ndarray) – Service time matrix (M x R); D[i, r] is the mean service time of class r at server i

  • strategies (List) – Per-server scheduling strategies (length M)

  • S (numpy.ndarray | None) – Optional per-server multiplicity (M,) or (M, 1); defaults to all-1

  • dispatching (RoutingStrategy) – Dispatching policy applied at the router (defaults to RAND)

Returns:

Configured open server-farm model

Return type:

Network

static clusterPs(lambda_rates, D, S=None, dispatching=None)

Open PS cluster (single-server queues unless S overrides multiplicity).

static clusterFcfs(lambda_rates, D, S=None, dispatching=None)

Open FCFS cluster.

static clusterClosed(N, Z, D, strategies, S=None, dispatching=None)

Create a closed server-farm network: Think -> Dispatcher -> Servers -> Think.

Parameters:
  • N (numpy.ndarray) – Per-class population (1, R) or (R,)

  • Z (numpy.ndarray) – Per-class think times (1, R) or (R,)

  • D (numpy.ndarray) – Service time matrix (M, R)

  • strategies (List) – Per-server scheduling strategies (length M)

  • S (numpy.ndarray | None) – Optional per-server multiplicity (M,)

  • dispatching (RoutingStrategy) – Dispatching policy (defaults to RAND)

class Ensemble[source]

Bases: object

Static helpers for combining independent network models.

static merge(models)[source]

Combine a list of independent Network models into a single Network.

Node and class names are prefixed with their model name to prevent conflicts; all Source and Sink nodes are merged into single MergedSource and MergedSink nodes.

Parameters:

models – list of Network models to merge.

Returns:

A new Network containing the disconnected subnetworks.

References

MATLAB: matlab/src/lang/Ensemble.m (merge) Java: java/src/main/java/jline/lang/Ensemble.java (merge)

Node Classes

class Node(node_type, name='')[source]

Bases: NetworkElement

Abstract base class for network nodes.

Initialize a node.

Parameters:
  • node_type (NodeType) – Type of node (from NodeType enum)

  • name (str) – Node name

__init__(node_type, name='')[source]

Initialize a node.

Parameters:
  • node_type (NodeType) – Type of node (from NodeType enum)

  • name (str) – Node name

__index__()[source]

Return node/station index for Python array indexing.

Returns station index if available (for Station subclasses), otherwise returns node index.

property node_type: NodeType

Get the node type.

set_model(model)[source]

Link this node to a network model.

Parameters:

model – Network instance

is_stateful()[source]

Check if node is stateful (can have jobs).

is_station()[source]

Check if node is a station (can serve jobs).

Create a link from this node to another node.

Parameters:

node_to – Destination node

set_routing(jobclass, strategy, *params)[source]

Set routing strategy for a job class.

Parameters:
  • jobclass (JobClass) – Job class

  • strategy (RoutingStrategy) – Routing strategy (RAND, PROB, etc.)

  • params – Additional parameters (depends on strategy) For WRROBIN: (destination_node, weight) - can be called multiple times

get_routing(jobclass)[source]

Get routing strategy for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Tuple of (strategy, parameters)

Return type:

Tuple[RoutingStrategy, tuple]

get_routing_weight(jobclass, destination)[source]

Get the WRROBIN routing weight for a class and destination (default 1.0).

getRoutingWeight(jobclass, destination)

Get the WRROBIN routing weight for a class and destination (default 1.0).

get_prob_routing(jobclass)[source]

Get probabilistic routing for a job class as {destination: prob}.

getProbRouting(jobclass)

Get probabilistic routing for a job class as {destination: prob}.

set_prob_routing(jobclass, destination, prob)[source]

Set probabilistic routing to a destination node.

Parameters:
  • jobclass (JobClass) – Job class

  • destination – Destination node

  • prob (float) – Routing probability (0 to 1)

setModel(model)

Link this node to a network model.

Parameters:

model – Network instance

isStateful()

Check if node is stateful (can have jobs).

isStation()

Check if node is a station (can serve jobs).

getRouting(jobclass)

Get routing strategy for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Tuple of (strategy, parameters)

Return type:

Tuple[RoutingStrategy, tuple]

class Source(model, name)[source]

Bases: Station

Source node for external arrivals.

A Source represents the entry point for open-class jobs. Each network can have at most one Source node.

Initialize a Source node.

Parameters:
  • model – Network instance

  • name (str) – Source node name

__init__(model, name)[source]

Initialize a Source node.

Parameters:
  • model – Network instance

  • name (str) – Source node name

set_arrival(jobclass, distribution)[source]

Set arrival distribution for a job class.

Parameters:
  • jobclass (JobClass) – Job class

  • distribution – Arrival distribution (Exp, Erlang, etc.)

set_arrival_batch(jobclass, batch_size)[source]

Set a batch-size law for a class, turning each arrival epoch into the simultaneous release of a batch of jobs.

The interarrival distribution set by set_arrival() keeps spacing the epochs; this decides how many jobs each epoch releases. Geometric interarrivals with a Geometric batch size is the Geo^X arrival stream, whose analytical counterpart is line_solver.api.qsys.qsys_geoxgeo1().

The batch size must be supported on {1,2,…}: an epoch that releases no job is not an arrival epoch, so a law that can return zero is rejected rather than clamped.

Parameters:
  • jobclass (JobClass) – Job class

  • batch_size – Batch-size distribution, or None to restore single arrivals

get_arrival_batch(jobclass)[source]

Return the batch-size law bound to a class, or None for single arrivals.

set_marked_arrival(mmap, classes)[source]

Bind a MarkedMAP with K marks to K open classes: mark k emits jobs of classes[k-1], with all marks driven by one shared modulating chain. Mirrors MATLAB Source.setMarkedArrival.

Parameters:
  • mmap – MarkedMAP/MMAP arrival process

  • classes – list of K distinct OpenClass instances, ordered by mark

get_marked_process()[source]

Get the shared MarkedMAP bound via set_marked_arrival, or None.

get_marked_classes()[source]

Get the classes bound to marks 1..K of the marked process, or None.

setMarkedArrival(mmap, classes)

Bind a MarkedMAP with K marks to K open classes: mark k emits jobs of classes[k-1], with all marks driven by one shared modulating chain. Mirrors MATLAB Source.setMarkedArrival.

Parameters:
  • mmap – MarkedMAP/MMAP arrival process

  • classes – list of K distinct OpenClass instances, ordered by mark

get_arrival(jobclass)[source]

Get arrival distribution for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Arrival distribution or None if not set

arrival_process(jobclass)

Get the arrival process (distribution) for a job class.

get_arrival_rates()[source]

Get arrival rates (1/mean) for all classes.

Returns:

Dict mapping classes to arrival rates

Return type:

Dict[JobClass, float]

getArrival(jobclass)

Get arrival distribution for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Arrival distribution or None if not set

getArrivalRates()

Get arrival rates (1/mean) for all classes.

Returns:

Dict mapping classes to arrival rates

Return type:

Dict[JobClass, float]

setArrivalBatch(jobclass, batch_size)

Set a batch-size law for a class, turning each arrival epoch into the simultaneous release of a batch of jobs.

The interarrival distribution set by set_arrival() keeps spacing the epochs; this decides how many jobs each epoch releases. Geometric interarrivals with a Geometric batch size is the Geo^X arrival stream, whose analytical counterpart is line_solver.api.qsys.qsys_geoxgeo1().

The batch size must be supported on {1,2,…}: an epoch that releases no job is not an arrival epoch, so a law that can return zero is rejected rather than clamped.

Parameters:
  • jobclass (JobClass) – Job class

  • batch_size – Batch-size distribution, or None to restore single arrivals

getArrivalBatch(jobclass)

Return the batch-size law bound to a class, or None for single arrivals.

class Queue(model, name, sched_strategy=SchedStrategy.FCFS)[source]

Bases: Station

Queue station for customer service.

A Queue represents a queueing station with one or more servers and configurable scheduling strategy.

Initialize a Queue node.

Parameters:
  • model – Network instance

  • name (str) – Queue name

  • sched_strategy (SchedStrategy) – Scheduling strategy (default: FCFS)

Raises:

ValueError – If scheduling strategy is invalid

__init__(model, name, sched_strategy=SchedStrategy.FCFS)[source]

Initialize a Queue node.

Parameters:
  • model – Network instance

  • name (str) – Queue name

  • sched_strategy (SchedStrategy) – Scheduling strategy (default: FCFS)

Raises:

ValueError – If scheduling strategy is invalid

set_sched_strategy(strategy)[source]

Set scheduling strategy.

Parameters:

strategy (SchedStrategy) – Scheduling strategy (FCFS, LCFS, PS, etc.)

get_sched_policy()[source]

Get scheduling policy (preemptive or non-preemptive).

set_service(jobclass, distribution=None, weight=None)[source]

Set service time distribution for a job class.

On a pass-and-swap (PAS) queue, call as set_service(mu) where mu is a callable taking the ordered state vector c (a list/array of class indices, c[0] the oldest job) and returning the scalar total service rate mu(c). Per-class service distributions are not used by an order-independent/PAS queue.

Parameters:
  • jobclass (JobClass) – Job class, or the mu(c) callable on a PAS queue

  • distribution – Service distribution (Exp, Erlang, HyperExp, etc.) or Workflow for activity-based distributions

  • weight (float) – Optional weight/scale factor for the distribution

service_process(jobclass)

Get the service process (distribution) for a job class (wrapper-compatible name).

get_service(jobclass)[source]

Get service distribution for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Service distribution or None if not set

set_item_service_rate(cache, jobin_class, item, service_rate)[source]

Override, at this queue, the retrieval service rate for a single item of the read class jobin_class in cache’s retrieval system. The default (when not overridden) is the read class’s own service distribution at this queue. item is 0-based.

setItemServiceRate(cache, jobin_class, item, service_rate)

Override, at this queue, the retrieval service rate for a single item of the read class jobin_class in cache’s retrieval system. The default (when not overridden) is the read class’s own service distribution at this queue. item is 0-based.

set_strategy_param(jobclass, param)[source]

Set scheduling parameter for a job class.

For PS/DPS/GPS: weight or priority parameter For other strategies: may be unused

Parameters:
  • jobclass (JobClass) – Job class

  • param – Scheduling parameter (weight, priority, etc.)

get_strategy_param(jobclass)[source]

Get scheduling parameter for a job class.

set_swap_graph(graph)[source]

Set the class compatibility/swap graph of a pass-and-swap (PAS) queue.

Parameters:

graph – (nclasses x nclasses) adjacency matrix; entry (r,s) nonzero iff, upon completion of a class-r job, a waiting class-s job may take its place (order-independent swap). Undirected; self-loops allowed.

get_swap_graph()[source]

Return the (nclasses x nclasses) swap graph of a PAS queue, or None.

set_service_rate_function(mu_fun)[source]

Set the total service rate function mu(c) of a pass-and-swap (PAS) queue.

Parameters:

mu_fun – callable taking the ordered state vector c (list/array of class indices, c[0] oldest) and returning the scalar total service rate mu(c). The rate of position i is the increment Delta_mu(c[:i]) = mu(c[:i]) - mu(c[:i-1]).

get_service_rate_function()[source]

Return the mu(c) service rate function of a PAS queue, or None.

check_perm_invariance(Nvec, cap)[source]

Check the order-independence (OI) condition on the service rate mu(c): the rate of the job in position j must depend only on the jobs at or ahead of it (positions 1..j) and not on those behind. Since the position-j rate is the prefix increment mu(c[:j]) - mu(c[:j-1]), tail-independence is structural; the substantive requirement is that this increment be independent of the order of the jobs ahead, which (by induction on prefix length) is equivalent to mu(c) being permutation- invariant. Enumerates the reachable multisets (per-class counts <= Nvec, total <= cap) when small, otherwise samples and returns partial=True. Returns (ok, badc, partial).

is_service_defined(jobclass)[source]

Check if service distribution is defined for a class.

is_service_disabled(jobclass)[source]

Check if service is explicitly disabled for a class.

get_service_rates()[source]

Get mean service rates for all classes.

Returns:

Dict mapping classes to mean service rates

Return type:

Dict[JobClass, float]

set_number_of_servers(value)[source]

Set the number of servers. Matches MATLAB Queue.setNumServers: DPS/GPS scheduling does not admit multi-server stations.

set_limit(limit)[source]

Set the maximum number of jobs in service for LPS (Limited Processor Sharing) scheduling. Mirrors MATLAB Queue.setLimit: the limit is stored as the queue-level scheduling parameter (schedparam column 1).

get_limit()[source]

Return the LPS concurrency limit set via set_limit, or numberOfServers when no explicit limit was set (matching MATLAB Queue.getLimit).

getSchedPolicy()

Get scheduling policy (preemptive or non-preemptive).

getService(jobclass)

Get service distribution for a job class.

Parameters:

jobclass (JobClass) – Job class

Returns:

Service distribution or None if not set

setStrategyParam(jobclass, param)

Set scheduling parameter for a job class.

For PS/DPS/GPS: weight or priority parameter For other strategies: may be unused

Parameters:
  • jobclass (JobClass) – Job class

  • param – Scheduling parameter (weight, priority, etc.)

getStrategyParam(jobclass)

Get scheduling parameter for a job class.

getServiceRates()

Get mean service rates for all classes.

Returns:

Dict mapping classes to mean service rates

Return type:

Dict[JobClass, float]

setSwapGraph(graph)

Set the class compatibility/swap graph of a pass-and-swap (PAS) queue.

Parameters:

graph – (nclasses x nclasses) adjacency matrix; entry (r,s) nonzero iff, upon completion of a class-r job, a waiting class-s job may take its place (order-independent swap). Undirected; self-loops allowed.

getSwapGraph()

Return the (nclasses x nclasses) swap graph of a PAS queue, or None.

setServiceRateFunction(mu_fun)

Set the total service rate function mu(c) of a pass-and-swap (PAS) queue.

Parameters:

mu_fun – callable taking the ordered state vector c (list/array of class indices, c[0] oldest) and returning the scalar total service rate mu(c). The rate of position i is the increment Delta_mu(c[:i]) = mu(c[:i]) - mu(c[:i-1]).

getServiceRateFunction()

Return the mu(c) service rate function of a PAS queue, or None.

set_num_servers(value)

Set the number of servers. Matches MATLAB Queue.setNumServers: DPS/GPS scheduling does not admit multi-server stations.

setLimit(limit)

Set the maximum number of jobs in service for LPS (Limited Processor Sharing) scheduling. Mirrors MATLAB Queue.setLimit: the limit is stored as the queue-level scheduling parameter (schedparam column 1).

getLimit()

Return the LPS concurrency limit set via set_limit, or numberOfServers when no explicit limit was set (matching MATLAB Queue.getLimit).

is_heterogeneous()[source]

Check if this queue has heterogeneous servers.

Returns:

True if server types have been defined

Return type:

bool

add_server_type(server_type)[source]

Add a server type to this queue.

Parameters:

server_type – ServerType object to add

Raises:

ValueError – If server type is already in queue

get_server_types()[source]

Get the list of server types.

set_hetero_sched_policy(policy)[source]

Set the heterogeneous scheduling policy.

Parameters:

policy – HeteroSchedPolicy value

get_hetero_sched_policy()[source]

Get the heterogeneous scheduling policy.

set_hetero_service(jobclass, server_type, distribution)[source]

Set service distribution for a specific job class and server type.

Parameters:
  • jobclass – Job class

  • server_type – ServerType object

  • distribution – Service distribution

get_hetero_service(jobclass, server_type)[source]

Get service distribution for a specific job class and server type.

Parameters:
  • jobclass – Job class

  • server_type – ServerType object

Returns:

Service distribution or None

get_total_num_of_servers()[source]

Get total number of servers across all server types.

Returns:

Total server count

Return type:

int

isHeterogeneous()

Check if this queue has heterogeneous servers.

Returns:

True if server types have been defined

Return type:

bool

addServerType(server_type)

Add a server type to this queue.

Parameters:

server_type – ServerType object to add

Raises:

ValueError – If server type is already in queue

getServerTypes()

Get the list of server types.

setHeteroSchedPolicy(policy)

Set the heterogeneous scheduling policy.

Parameters:

policy – HeteroSchedPolicy value

getHeteroSchedPolicy()

Get the heterogeneous scheduling policy.

setHeteroService(jobclass, server_type, distribution)

Set service distribution for a specific job class and server type.

Parameters:
  • jobclass – Job class

  • server_type – ServerType object

  • distribution – Service distribution

getHeteroService(jobclass, server_type)

Get service distribution for a specific job class and server type.

Parameters:
  • jobclass – Job class

  • server_type – ServerType object

Returns:

Service distribution or None

getTotalNumOfServers()

Get total number of servers across all server types.

Returns:

Total server count

Return type:

int

set_polling_type(polling_type, k=None)[source]

Set the polling type for this queue.

Parameters:
  • polling_type – PollingType enum value (EXHAUSTIVE, GATED, KLIMITED)

  • k – For KLIMITED polling, the maximum number of jobs to serve (default: 1)

get_polling_type()[source]

Get the polling type for this queue.

set_polling_k(k)[source]

Set the k parameter for k-limited polling (wrapper-compatible name).

set_switchover(from_class, to_class_or_dist, distribution=None)[source]

Set switchover time between job classes.

Can be called as: - set_switchover(from_class, to_class, distribution) - for class-to-class switchover - set_switchover(jobclass, distribution) - for single class switchover time

Parameters:
  • from_class – Source job class

  • to_class_or_dist – Target job class, OR distribution if only 2 args

  • distribution – Switchover time distribution (optional if 2 args)

set_delay_off(jobclass, setup_time, delay_off_time)[source]

Set setup and delay-off time distributions for a job class.

Models a vacation queue: when a server finishes serving class r and no more class r jobs are waiting, the server enters a delay-off period. When a new class r job arrives during delay-off, the server goes through setup before serving.

Parameters:
  • jobclass – Job class

  • setup_time – Distribution for setup time

  • delay_off_time – Distribution for delay-off time

setDelayOff(jobclass, setup_time, delay_off_time)

Set setup and delay-off time distributions for a job class.

Models a vacation queue: when a server finishes serving class r and no more class r jobs are waiting, the server enters a delay-off period. When a new class r job arrives during delay-off, the server goes through setup before serving.

Parameters:
  • jobclass – Job class

  • setup_time – Distribution for setup time

  • delay_off_time – Distribution for delay-off time

get_setup_time(jobclass)[source]

Get setup time distribution for a job class.

getSetupTime(jobclass)

Get setup time distribution for a job class.

get_delay_off_time(jobclass)[source]

Get delay-off time distribution for a job class.

getDelayOffTime(jobclass)

Get delay-off time distribution for a job class.

is_delay_off_enabled()[source]

Return True if setup and delay-off times are both configured.

isDelayOffEnabled()

Return True if setup and delay-off times are both configured.

set_prob_routing(jobclass, destination, prob)[source]

Set probabilistic routing to a destination node.

Parameters:
  • jobclass – Job class

  • destination – Destination node

  • prob (float) – Routing probability (0 to 1)

get_prob_routing(jobclass)[source]

Get probabilistic routing for a job class.

set_state(state)[source]

Set initial state for this node.

Parameters:

state – Array of initial job counts per class

set_routing_weight(jobclass, destination, weight)[source]

Set routing weight for weighted round-robin routing.

Parameters:
  • jobclass (JobClass) – Job class

  • destination – Destination node

  • weight (float) – Routing weight for this destination

get_routing_weight(jobclass, destination)[source]

Get routing weight for a job class and destination.

set_balking(jobclass, strategy, thresholds)[source]

Configure balking for a job class.

Parameters:
  • jobclass – JobClass object

  • strategy – BalkingStrategy enum value

  • thresholds – List of (minJobs, maxJobs, probability) tuples

get_balking(jobclass)[source]

Get balking config for a job class. Returns (strategy, thresholds) or (None, []).

has_balking(jobclass)[source]

Check if a job class has balking configured.

set_retrial(jobclass, delay_distribution, max_attempts=-1)[source]

Configure retrial for a job class.

Parameters:
  • jobclass – JobClass object

  • delay_distribution – Distribution for retrial delay

  • max_attempts – Maximum retrial attempts (-1 = unlimited)

get_retrial(jobclass)[source]

Get retrial config for a job class. Returns (delay_dist, max_attempts) or (None, -1).

has_retrial(jobclass)[source]

Check if a job class has retrial configured.

set_orbit_impatience(jobclass, distribution)[source]

Set the impatience (abandonment) rate for customers in the orbit.

This is separate from queue patience (reneging from the waiting queue). Used in BMAP/PH/N/N retrial queues where customers in the orbit may abandon before successfully retrying.

Parameters:
  • jobclass – JobClass object

  • distribution – Distribution for orbit abandonment time (e.g. Exp(gamma)). Modulated processes (BMAP, MAP, DMAP, MMPP2) are not supported.

setOrbitImpatience(jobclass, distribution)

Set the impatience (abandonment) rate for customers in the orbit.

This is separate from queue patience (reneging from the waiting queue). Used in BMAP/PH/N/N retrial queues where customers in the orbit may abandon before successfully retrying.

Parameters:
  • jobclass – JobClass object

  • distribution – Distribution for orbit abandonment time (e.g. Exp(gamma)). Modulated processes (BMAP, MAP, DMAP, MMPP2) are not supported.

get_orbit_impatience(jobclass)[source]

Get the orbit-impatience distribution for a job class (or None).

getOrbitImpatience(jobclass)

Get the orbit-impatience distribution for a job class (or None).

has_orbit_impatience(jobclass)[source]

Check if a job class has orbit impatience configured at this queue.

hasOrbitImpatience(jobclass)

Check if a job class has orbit impatience configured at this queue.

set_batch_reject_probability(jobclass, p)[source]

Set the batch rejection probability for a job class.

Used in BMAP/PH/N/N retrial queues. When a batch of size k arrives and only m < k servers are free:

  • with probability p the entire batch is rejected to the orbit;

  • with probability (1-p) m customers are admitted and k-m go to orbit.

Parameters:
  • jobclass – JobClass object

  • p – Probability in [0,1] that the batch is rejected rather than partially admitted. Default is 0 (partial admission allowed).

setBatchRejectProbability(jobclass, p)

Set the batch rejection probability for a job class.

Used in BMAP/PH/N/N retrial queues. When a batch of size k arrives and only m < k servers are free:

  • with probability p the entire batch is rejected to the orbit;

  • with probability (1-p) m customers are admitted and k-m go to orbit.

Parameters:
  • jobclass – JobClass object

  • p – Probability in [0,1] that the batch is rejected rather than partially admitted. Default is 0 (partial admission allowed).

get_batch_reject_probability(jobclass)[source]

Get the batch reject probability for a job class (0 if not set).

getBatchRejectProbability(jobclass)

Get the batch reject probability for a job class (0 if not set).

set_patience(jobclass, distribution, impatience_type=None)[source]

Set patience distribution for a job class.

Parameters:
  • jobclass – JobClass object

  • distribution – Patience distribution

  • impatience_type – ImpatienceType enum value (default: RENEGING)

get_patience(jobclass)[source]

Get patience distribution for a job class, or None.

get_impatience_type(jobclass)[source]

Get impatience type for a job class, or None.

has_patience(jobclass)[source]

Check if a job class has patience configured.

set_immediate_feedback(value)[source]

Configure immediate feedback for this queue.

When enabled, a job that routes back to this queue (self-loop) stays in service instead of re-entering the queue.

Parameters:

value – bool (enable/disable for all classes), JobClass (enable for specific class), or list of JobClass (enable for specific classes)

has_immediate_feedback(jobclass=None)[source]

Check if immediate feedback is enabled.

Parameters:

jobclass – If provided, check for specific class. If None, check if any class has it.

get_immediate_feedback_classes()[source]

Get set of class indices with immediate feedback enabled, or ‘all’.

getPollingType()

Get the polling type for this queue.

getProbRouting(jobclass)

Get probabilistic routing for a job class.

setRoutingWeight(jobclass, destination, weight)

Set routing weight for weighted round-robin routing.

Parameters:
  • jobclass (JobClass) – Job class

  • destination – Destination node

  • weight (float) – Routing weight for this destination

getRoutingWeight(jobclass, destination)

Get routing weight for a job class and destination.

setBalking(jobclass, strategy, thresholds)

Configure balking for a job class.

Parameters:
  • jobclass – JobClass object

  • strategy – BalkingStrategy enum value

  • thresholds – List of (minJobs, maxJobs, probability) tuples

getBalking(jobclass)

Get balking config for a job class. Returns (strategy, thresholds) or (None, []).

hasBalking(jobclass)

Check if a job class has balking configured.

setRetrial(jobclass, delay_distribution, max_attempts=-1)

Configure retrial for a job class.

Parameters:
  • jobclass – JobClass object

  • delay_distribution – Distribution for retrial delay

  • max_attempts – Maximum retrial attempts (-1 = unlimited)

getRetrial(jobclass)

Get retrial config for a job class. Returns (delay_dist, max_attempts) or (None, -1).

hasRetrial(jobclass)

Check if a job class has retrial configured.

setPatience(jobclass, distribution, impatience_type=None)

Set patience distribution for a job class.

Parameters:
  • jobclass – JobClass object

  • distribution – Patience distribution

  • impatience_type – ImpatienceType enum value (default: RENEGING)

getPatience(jobclass)

Get patience distribution for a job class, or None.

hasPatience(jobclass)

Check if a job class has patience configured.

getImpatienceType(jobclass)

Get impatience type for a job class, or None.

setImmediateFeedback(value)

Configure immediate feedback for this queue.

When enabled, a job that routes back to this queue (self-loop) stays in service instead of re-entering the queue.

Parameters:

value – bool (enable/disable for all classes), JobClass (enable for specific class), or list of JobClass (enable for specific classes)

hasImmediateFeedback(jobclass=None)

Check if immediate feedback is enabled.

Parameters:

jobclass – If provided, check for specific class. If None, check if any class has it.

getImmediateFeedbackClasses()

Get set of class indices with immediate feedback enabled, or ‘all’.

class Delay(model, name)[source]

Bases: Queue

Delay node (infinite server).

A Delay represents an infinite-capacity queue (think time station in closed models). All jobs immediately begin service without queueing.

Initialize a Delay node.

Parameters:
  • model – Network instance

  • name (str) – Delay node name

__init__(model, name)[source]

Initialize a Delay node.

Parameters:
  • model – Network instance

  • name (str) – Delay node name

set_number_of_servers(value)[source]

Set number of servers (always infinity for Delay).

Parameters:

value (int) – Ignored (always set to infinity)

Raises:

ValueError – If not infinity

class Sink(model, name)[source]

Bases: Node

Sink node for job departure.

A Sink is the exit point for open-class jobs. Each network can have at most one Sink node.

Initialize a Sink node.

Parameters:
  • model – Network instance

  • name (str) – Sink node name

__init__(model, name)[source]

Initialize a Sink node.

Parameters:
  • model – Network instance

  • name (str) – Sink node name

class Router(model, name)[source]

Bases: Node

Router node for routing decisions.

A Router is a node that routes jobs without service delay. Can be used for probabilistic routing and routing-dependent decisions.

Initialize a Router node.

Parameters:
  • model – Network instance

  • name (str) – Router node name

__init__(model, name)[source]

Initialize a Router node.

Parameters:
  • model – Network instance

  • name (str) – Router node name

class Fork(model, name)[source]

Bases: Node

Fork node for parallel processing.

A Fork splits an incoming job into multiple parallel tasks that must be synchronized at a corresponding Join node.

Initialize a Fork node.

Parameters:
  • model – Network instance

  • name (str) – Fork node name

__init__(model, name)[source]

Initialize a Fork node.

Parameters:
  • model – Network instance

  • name (str) – Fork node name

set_state(state)[source]

Set Fork state (FJ tag-augmented copies only).

get_state_prior()[source]

Get Fork state prior (FJ tag-augmented copies only).

set_state_prior(prior)[source]

Set Fork state prior (FJ tag-augmented copies only).

setStatePrior(prior)

Set Fork state prior (FJ tag-augmented copies only).

get_state_space()[source]

Get Fork state space (FJ tag-augmented copies only).

set_state_space(space)[source]

Set Fork state space (FJ tag-augmented copies only).

Set number of tasks spawned per outgoing link (experimental).

Parameters:

ntasks (numpy.ndarray) – Array with task counts for each link

Get tasks per link.

property capacity: float

Get capacity.

class Join(model, name, fork=None)[source]

Bases: Station

Join node for parallel processing synchronization.

A Join waits for all parallel tasks from a corresponding Fork before releasing the job downstream.

Initialize a Join node.

Parameters:
  • model – Network instance

  • name (str) – Join node name

  • fork (Fork | None) – Associated Fork node (optional)

__init__(model, name, fork=None)[source]

Initialize a Join node.

Parameters:
  • model – Network instance

  • name (str) – Join node name

  • fork (Fork | None) – Associated Fork node (optional)

set_fork(fork)[source]

Set associated Fork node.

Parameters:

fork (Fork) – Fork node to pair with

get_fork()[source]

Get associated Fork node.

set_strategy(jobclass, strategy)[source]

Set join strategy for a job class.

Parameters:
  • jobclass (JobClass) – Job class

  • strategy (JoinStrategy) – Join strategy (STD, QUORUM, etc.)

get_strategy(jobclass)[source]

Get join strategy for a job class.

set_required(jobclass, nrequired)[source]

Set required number of tasks to wait for (quorum join).

Parameters:
  • jobclass (JobClass) – Job class

  • nrequired (int) – Number of required tasks (-1 = all)

get_required(jobclass)[source]

Get required task count.

class Cache(model, name, num_items, item_level_cap, replacement_strategy=ReplacementStrategy.LRU)[source]

Bases: Station

Multi-level cache node with configurable replacement strategy.

A Cache node models content caching behavior where arriving jobs request items from a catalog. Items may be cached (hit) or fetched (miss), with jobs potentially switching classes based on hit/miss outcomes.

The cache supports multiple levels (hierarchy) with different capacities and uses configurable replacement policies (LRU, FIFO, RR, SFIFO).

Cache analysis can be performed using algorithms from api.cache: - cache_mva: Mean Value Analysis for hit/miss probabilities - cache_erec: Exact recursive computation - cache_spm: Singular Perturbation Method (approximate)

Parameters:
  • model – Network instance

  • name (str) – Cache node name

  • num_items (int) – Number of items in the catalog (n)

  • item_level_cap (int | numpy.ndarray | list) – Capacity of each cache level (int or array)

  • replacement_strategy (ReplacementStrategy) – Cache replacement policy (LRU, FIFO, RR, SFIFO)

Example

>>> model = Network('CacheModel')
>>> cache = Cache(model, 'MyCache', num_items=100,
...               item_level_cap=10, replacement_strategy=ReplacementStrategy.LRU)
>>> job_class = ClosedClass(model, 'Request', 5, delay)
>>> hit_class = ClosedClass(model, 'Hit', 0, delay)
>>> miss_class = ClosedClass(model, 'Miss', 0, delay)
>>> cache.set_read(job_class, Zipf(1.2, 100))  # Zipf popularity
>>> cache.set_hit_class(job_class, hit_class)
>>> cache.set_miss_class(job_class, miss_class)
Reference:
  • Cache algorithms: Che, H. et al. “Hierarchical Web Caching Systems”

  • TTL approximation: Fofack et al. “Analysis of TTL-based Cache Networks”

Initialize a Cache node.

Parameters:
  • model – Network instance

  • name (str) – Cache node name

  • num_items (int) – Total number of items in catalog (n >= 1)

  • item_level_cap (int | numpy.ndarray | list) – Capacity per cache level. Can be: - int: Single-level cache with given capacity - array/list: Multi-level cache with capacity per level

  • replacement_strategy (ReplacementStrategy) – Replacement policy (default: LRU)

Raises:

ValueError – If num_items < 1 or item_level_cap invalid

__init__(model, name, num_items, item_level_cap, replacement_strategy=ReplacementStrategy.LRU)[source]

Initialize a Cache node.

Parameters:
  • model – Network instance

  • name (str) – Cache node name

  • num_items (int) – Total number of items in catalog (n >= 1)

  • item_level_cap (int | numpy.ndarray | list) – Capacity per cache level. Can be: - int: Single-level cache with given capacity - array/list: Multi-level cache with capacity per level

  • replacement_strategy (ReplacementStrategy) – Replacement policy (default: LRU)

Raises:

ValueError – If num_items < 1 or item_level_cap invalid

is_station()[source]

Check if node is a station.

Cache nodes are NOT stations in LINE’s semantics, matching MATLAB behavior. They are stateful nodes that immediately process arriving jobs (class switching based on cache hit/miss) but don’t queue or serve jobs like stations.

Returns:

Cache is a stateful non-station node

Return type:

False

property num_items: int

Get the number of items in the catalog.

property num_levels: int

Get the number of cache levels.

property item_level_cap: numpy.ndarray

Get the capacity array for each cache level.

property total_capacity: int

Get the total cache capacity across all levels.

property replacement_strategy: ReplacementStrategy

Get the cache replacement strategy.

set_hit_class(input_class, output_class)[source]

Set the output class for cache hits.

When a job of input_class experiences a cache hit, it transitions to output_class for further processing.

Parameters:
  • input_class (JobClass) – Incoming job class making the request

  • output_class (JobClass) – Resulting job class after cache hit

get_hit_class(input_class)[source]

Get the output class for cache hits.

set_miss_class(input_class, output_class)[source]

Set the output class for cache misses.

When a job of input_class experiences a cache miss, it transitions to output_class for further processing.

Parameters:
  • input_class (JobClass) – Incoming job class making the request

  • output_class (JobClass) – Resulting job class after cache miss

get_miss_class(input_class)[source]

Get the output class for cache misses.

set_read(jobclass, distribution)[source]

Set the read (popularity) distribution for a job class.

The distribution determines which items are requested by jobs of the given class. Typically a discrete distribution like Zipf.

Parameters:
  • jobclass (JobClass) – Job class making requests

  • distribution – Popularity distribution (e.g., Zipf, Uniform)

get_read(jobclass)[source]

Get the read distribution for a job class.

set_access_prob(access_prob)[source]

Set the access probability matrix directly.

Alternative to set_read() for specifying item access probabilities as a matrix.

Parameters:

access_prob (numpy.ndarray) – (num_items, num_classes) probability matrix. Each column should sum to 1.

set_admission_prob(q)[source]

Set the q-LRU admission probability.

Probability q in [0, 1] of admitting a missed item into the cache. Only used when the replacement strategy is QLRU.

get_access_prob()[source]

Get the access probability matrix.

set_access_graph(graph)[source]

Set the per-item access-cost (list-move) graph.

Mirrors the MATLAB Cache constructor’s graph argument: one (h+1) x (h+1) matrix per item, shared by all job classes, where h is the number of cache lists. Row 1 governs miss insertion (column 1 = do not cache, column 1+l = insert into list l); row 1+i governs hits in list i (column 1+j = move the item to list j >= i).

Parameters:

graph – sequence of num_items matrices, each (h+1) x (h+1).

get_access_graph()[source]

Return the per-item access-cost graph, or None if not set.

set_result_hit_prob(hit_prob)[source]

Set the computed hit probability (called by solver).

set_result_miss_prob(miss_prob)[source]

Set the computed miss probability (called by solver).

set_result_delayed_hit_prob(delayed_hit_prob)[source]

Set the computed delayed-hit fraction (retrieval system; called by solver).

set_result_hit_prob_list(hit_prob_list)[source]

Set the computed per-list (per-level) hit fractions [classes x lists].

get_delayed_hit_ratio()[source]

Get the delayed-hit fraction per class (None when no retrieval system).

get_hit_ratio_by_list()[source]

Get the per-class, per-list hit fraction matrix [classes x lists].

set_result_item_prob(item_prob)[source]

Set the per-item occupancy [items x (lists+1)]; col 0 = miss, cols 1.. = per-list.

get_item_prob()[source]

Get the per-item occupancy matrix [items x (lists+1)] (col 0 = miss).

get_gamma_matrix(nclasses=1)[source]

Build the gamma (access factor) matrix for cache analysis.

The gamma matrix has shape (num_items, num_levels) and contains the cache access intensity factors used by cache_mva/cache_erec.

Parameters:

nclasses (int) – Number of job classes

Returns:

Gamma matrix for cache analysis algorithms

Return type:

numpy.ndarray

get_capacity_vector()[source]

Get the cache capacity vector.

Returns:

Array of cache level capacities

Return type:

numpy.ndarray

property total_cache_capacity: int

Total cache capacity (sum of per-level capacities).

property retrieval_system_capacity: int

Number of items that can be in the retrieval system simultaneously (0 when no retrieval system is configured).

set_result_residt(expected_latency)[source]

Set the computed expected latency (called by solver).

get_residt()[source]

Get the expected latency per class, or None if not computed yet.

reset()[source]

Clear solver result fields.

set_retrieval_class(input_class, output_class, item)[source]

Set the retrieval class for (item, input_class). item is 0-based.

get_retrieval_class(input_class, item)[source]

Get the retrieval class for (item, input_class).

set_retrieval_system(jobin_class, miss_class, queues)[source]

Initialise the retrieval system through which a request that misses the cache is fetched. While the retrieval is pending, repeat requests for the same item become delayed hits; after retrieval completes the job switches into miss_class.

Routing and service are NOT passed here; they are taken from the read class:
  • service: the read class’s service distribution at each queue. Call queue.set_service(jobin_class, ...) beforehand; override per item with queue.set_item_service_rate(cache, jobin_class, item, rate).

  • routing: the read class’s routing among the retrieval queues drawn in the top-level routing matrix P; override per item with set_item_routing_prob (pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit).

Parameters:
  • jobin_class (JobClass) – arrival JobClass routed through the retrieval system

  • miss_class (JobClass) – JobClass a completed retrieval transitions into

  • queues – a Queue or list of Queue nodes comprising the system

set_item_routing_probability(jobin_class, item, source, dest, probability)[source]

Probability of routing the retrieval class for item between two nodes of the retrieval system. source/dest are either a retrieval queue or the cache itself: pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit. item is 0-based. Requires a prior set_retrieval_system() call.

setRetrievalSystem(jobin_class, miss_class, queues)

Initialise the retrieval system through which a request that misses the cache is fetched. While the retrieval is pending, repeat requests for the same item become delayed hits; after retrieval completes the job switches into miss_class.

Routing and service are NOT passed here; they are taken from the read class:
  • service: the read class’s service distribution at each queue. Call queue.set_service(jobin_class, ...) beforehand; override per item with queue.set_item_service_rate(cache, jobin_class, item, rate).

  • routing: the read class’s routing among the retrieval queues drawn in the top-level routing matrix P; override per item with set_item_routing_prob (pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit).

Parameters:
  • jobin_class (JobClass) – arrival JobClass routed through the retrieval system

  • miss_class (JobClass) – JobClass a completed retrieval transitions into

  • queues – a Queue or list of Queue nodes comprising the system

getResidT()

Get the expected latency per class, or None if not computed yet.

setResultResidT(expected_latency)

Set the computed expected latency (called by solver).

setItemRoutingProbability(jobin_class, item, source, dest, probability)

Probability of routing the retrieval class for item between two nodes of the retrieval system. source/dest are either a retrieval queue or the cache itself: pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit. item is 0-based. Requires a prior set_retrieval_system() call.

set_item_routing_prob(jobin_class, item, source, dest, probability)

Probability of routing the retrieval class for item between two nodes of the retrieval system. source/dest are either a retrieval queue or the cache itself: pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit. item is 0-based. Requires a prior set_retrieval_system() call.

setItemRoutingProb(jobin_class, item, source, dest, probability)

Probability of routing the retrieval class for item between two nodes of the retrieval system. source/dest are either a retrieval queue or the cache itself: pass the cache as source for a cache->queue entry, or as dest for a queue->cache exit. item is 0-based. Requires a prior set_retrieval_system() call.

getHitClass(input_class)

Get the output class for cache hits.

getMissClass(input_class)

Get the output class for cache misses.

getRead(jobclass)

Get the read distribution for a job class.

setAccessProb(access_prob)

Set the access probability matrix directly.

Alternative to set_read() for specifying item access probabilities as a matrix.

Parameters:

access_prob (numpy.ndarray) – (num_items, num_classes) probability matrix. Each column should sum to 1.

getAccessProb()

Get the access probability matrix.

setResultHitProb(hit_prob)

Set the computed hit probability (called by solver).

setResultMissProb(miss_prob)

Set the computed miss probability (called by solver).

hit_ratio()

Get the hit ratio (probability) for each class.

Returns:

Hit probability array, or None if not computed yet.

Return type:

numpy.ndarray | None

miss_ratio()

Get the miss ratio (probability) for each class.

Returns:

Miss probability array, or None if not computed yet.

Return type:

numpy.ndarray | None

getNumItems()[source]

Get number of items (MATLAB compatibility).

getNumLevels()[source]

Get number of cache levels (MATLAB compatibility).

getCapacity()[source]

Get total cache capacity (MATLAB compatibility).

getReplacementStrategy()[source]

Get replacement strategy (MATLAB compatibility).

getItemLevelCap()[source]

Get per-level capacity array (MATLAB compatibility).

class ClassSwitch(model, name, cs_matrix=None)[source]

Bases: Node

ClassSwitch node for job class switching.

A ClassSwitch allows jobs to change class without service delay. Useful for modeling class-dependent routing and scheduling.

Initialize a ClassSwitch node.

Parameters:
  • model – Network instance

  • name (str) – ClassSwitch node name

  • cs_matrix – Optional K×K class switching probability matrix where element (i,j) is the probability that a job in class i switches to class j. If not provided, must be set later using set_class_switching_matrix().

__init__(model, name, cs_matrix=None)[source]

Initialize a ClassSwitch node.

Parameters:
  • model – Network instance

  • name (str) – ClassSwitch node name

  • cs_matrix – Optional K×K class switching probability matrix where element (i,j) is the probability that a job in class i switches to class j. If not provided, must be set later using set_class_switching_matrix().

init_class_switch_matrix()[source]

Initialize and return a class switching matrix.

Creates a K×K matrix of zeros where K is the number of classes. Use this to create a template that can be filled with switching probabilities before calling set_class_switching_matrix().

Returns:

K×K matrix initialized to zeros

Return type:

np.ndarray

Example

>>> csmatrix = cs_node.init_class_switch_matrix()
>>> csmatrix[0, 1] = 0.3  # 30% switch from class 0 to class 1
>>> csmatrix[0, 0] = 0.7  # 70% stay in class 0
>>> csmatrix[1, 0] = 1.0  # 100% switch from class 1 to class 0
>>> cs_node.set_class_switching_matrix(csmatrix)
init_class_switching_matrix()

Initialize and return a class switching matrix.

Creates a K×K matrix of zeros where K is the number of classes. Use this to create a template that can be filled with switching probabilities before calling set_class_switching_matrix().

Returns:

K×K matrix initialized to zeros

Return type:

np.ndarray

Example

>>> csmatrix = cs_node.init_class_switch_matrix()
>>> csmatrix[0, 1] = 0.3  # 30% switch from class 0 to class 1
>>> csmatrix[0, 0] = 0.7  # 70% stay in class 0
>>> csmatrix[1, 0] = 1.0  # 100% switch from class 1 to class 0
>>> cs_node.set_class_switching_matrix(csmatrix)
set_class_switching_matrix(cs_matrix)[source]

Set the class switching probability matrix.

Parameters:

cs_matrix (numpy.ndarray) – K×K matrix where element (i,j) is the probability that a job in class i switches to class j. Each row should sum to 1.0.

Example

>>> csmatrix = cs_node.init_class_switch_matrix()
>>> csmatrix[0, 0] = 0.7
>>> csmatrix[0, 1] = 0.3
>>> cs_node.set_class_switching_matrix(csmatrix)
get_class_switching_matrix()[source]

Get the current class switching matrix.

Returns:

The K×K switching matrix, or None if not set

Return type:

np.ndarray or None

getClassSwitchingMatrix()

Get the current class switching matrix.

Returns:

The K×K switching matrix, or None if not set

Return type:

np.ndarray or None

set_switch_probability(from_class, to_class, probability)[source]

Set the probability of switching from one class to another.

This is a convenience method that handles indexing automatically.

Parameters:
  • from_class – Source job class (object or 0-based index)

  • to_class – Target job class (object or 0-based index)

  • probability (float) – Switching probability (0.0 to 1.0)

Example

>>> cs_node.set_switch_probability(class1, class2, 0.3)
>>> cs_node.set_switch_probability(class1, class1, 0.7)
setSwitchProbability(from_class, to_class, probability)

Set the probability of switching from one class to another.

This is a convenience method that handles indexing automatically.

Parameters:
  • from_class – Source job class (object or 0-based index)

  • to_class – Target job class (object or 0-based index)

  • probability (float) – Switching probability (0.0 to 1.0)

Example

>>> cs_node.set_switch_probability(class1, class2, 0.3)
>>> cs_node.set_switch_probability(class1, class1, 0.7)
class Place(model, name, sched_strategy=None)[source]

Bases: Station

Place node for Stochastic Petri Nets.

A Place represents a location where tokens (jobs) can accumulate. Places have infinite capacity (like Delay nodes) and infinite servers.

In queueing network terms, a Place is similar to a delay station but tokens are processed when they move to Transitions.

Initialize a Place node.

Parameters:
  • model – Network instance

  • name (str) – Place name

  • sched_strategy – optional scheduling strategy of the embedded queue. When provided (and a service process is later assigned via set_service), the place becomes a queueing place (QPN semantics) rather than an ordinary/INF pass-through place.

__init__(model, name, sched_strategy=None)[source]

Initialize a Place node.

Parameters:
  • model – Network instance

  • name (str) – Place name

  • sched_strategy – optional scheduling strategy of the embedded queue. When provided (and a service process is later assigned via set_service), the place becomes a queueing place (QPN semantics) rather than an ordinary/INF pass-through place.

set_service(jobclass, distribution)[source]

Assign a service process to a token color, turning this ordinary place into a queueing place (QPN semantics). The embedded queue serves tokens under the place’s scheduling strategy; on completion tokens move to the depository from which output transitions consume them.

Parameters:
  • jobclass (JobClass) – token color (job class)

  • distribution – service-time distribution of the embedded queue

get_service(jobclass)[source]

Get the embedded-queue service distribution for a job class (or None).

getService(jobclass)

Get the embedded-queue service distribution for a job class (or None).

is_queueing()[source]

True if this place is a queueing place (has an embedded queue).

isQueueing()

True if this place is a queueing place (has an embedded queue).

set_departure_discipline(jobclass, discipline)[source]

Set the depository departure discipline for a token color.

setDepartureDiscipline(jobclass, discipline)

Set the depository departure discipline for a token color.

set_number_of_servers(k)[source]

Set the number of servers of the embedded queue (multiserver queueing place).

set_class_capacity(jobclass, capacity)[source]

Set per-class capacity limit.

Parameters:
  • jobclass (JobClass) – Job class

  • capacity (float) – Capacity for this class

set_drop_rule(jobclass, drop_rule)[source]

Set the per-class drop rule for a bounded place.

Determines what happens to a token that would exceed the place capacity (DropStrategy.DROP for a loss place, WAITQ/BAS/… for blocking). Mirrors MATLAB Place.setDropRule.

Parameters:
  • jobclass (JobClass) – token color (job class)

  • drop_rule – a DropStrategy value

set_state(state)[source]

Set initial token state for this place.

Parameters:

state – Array of initial token counts per class

set_marking(state)

Set initial token state for this place.

Parameters:

state – Array of initial token counts per class

setMarking(state)

Set initial token state for this place.

Parameters:

state – Array of initial token counts per class

class Transition(model, name)[source]

Bases: StatefulNode

Transition node for Stochastic Petri Nets.

A Transition consumes tokens from input Places and produces tokens to output Places according to defined firing modes.

Each Transition can have multiple firing modes, each with: - Enabling conditions: required tokens from input places - Inhibiting conditions: blocking conditions from places - Firing outcomes: tokens produced to output places - Timing distribution: delay before firing - Priority and weight for conflict resolution

Initialize a Transition node.

Parameters:
  • model – Network instance

  • name (str) – Transition name

__init__(model, name)[source]

Initialize a Transition node.

Parameters:
  • model – Network instance

  • name (str) – Transition name

add_mode(mode_name)[source]

Add a new firing mode to this transition.

Parameters:

mode_name (str) – Name for the new mode

Returns:

Mode object representing the new mode

Return type:

Mode

set_enabling_conditions(mode, jobclass, input_node, enabling_condition)[source]

Set enabling conditions for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • jobclass (JobClass) – Job class

  • input_node – Input Place node

  • enabling_condition (int) – Number of tokens required

set_inhibiting_conditions(mode, jobclass, input_node, inhibiting_condition)[source]

Set inhibiting conditions for a mode.

The transition cannot fire if the place has >= inhibiting_condition tokens.

Parameters:
  • mode – Mode object or index (1-based)

  • jobclass (JobClass) – Job class

  • input_node – Input Place node

  • inhibiting_condition (int) – Number of tokens that inhibit firing

set_firing_outcome(mode, jobclass, output_node, firing_outcome)[source]

Set firing outcome for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • jobclass (JobClass) – Job class

  • output_node – Output Place or Sink node

  • firing_outcome (int) – Number of tokens produced

set_distribution(mode, distribution)[source]

Set firing time distribution for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • distribution – Timing distribution (Exp, Erlang, etc.)

get_distribution(mode)[source]

Get firing time distribution for a mode.

getDistribution(mode)

Get firing time distribution for a mode.

set_number_of_servers(mode, num_servers)[source]

Set number of servers for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • num_servers (int) – Number of servers (or GlobalConstants.MaxInt for infinite)

set_timing_strategy(mode, timing_strategy)[source]

Set timing strategy for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • timing_strategy (TimingStrategy) – TIMED or IMMEDIATE

set_firing_priorities(mode, priority)[source]

Set firing priority for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • priority (float) – Priority value (higher = more priority)

set_firing_weights(mode, weight)[source]

Set firing weight for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • weight (float) – Weight for probabilistic selection among enabled modes

set_mode_names(mode, mode_name)[source]

Set name for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • mode_name (str) – New name for the mode

setModeNames(mode, mode_name)

Set name for a mode.

Parameters:
  • mode – Mode object or index (1-based)

  • mode_name (str) – New name for the mode

get_service_rates()[source]

Get service rates for all modes.

Returns:

Tuple of (map, mu, phi) lists for PH-type service rates

getServiceRates()

Get service rates for all modes.

Returns:

Tuple of (map, mu, phi) lists for PH-type service rates

Job Class Classes

class JobClass(model_or_type, name_or_jobclass_type=None, jobclass_type_or_prio=None, prio_or_deadline=None)[source]

Bases: NetworkElement

Abstract base class for job classes.

Initialize a job class.

Supports two signatures for compatibility: 1. (model, name, JobClassType, priority) - from classes.py 2. (jobclass_type, name, priority, deadline) - native implementation

Parameters:
  • model_or_type – Model instance or JobClassType

  • name_or_jobclass_type (str) – Class name or JobClassType

  • jobclass_type_or_prio – JobClassType or priority

  • prio_or_deadline – Priority or deadline

__init__(model_or_type, name_or_jobclass_type=None, jobclass_type_or_prio=None, prio_or_deadline=None)[source]

Initialize a job class.

Supports two signatures for compatibility: 1. (model, name, JobClassType, priority) - from classes.py 2. (jobclass_type, name, priority, deadline) - native implementation

Parameters:
  • model_or_type – Model instance or JobClassType

  • name_or_jobclass_type (str) – Class name or JobClassType

  • jobclass_type_or_prio – JobClassType or priority

  • prio_or_deadline – Priority or deadline

property jobclass_type: JobClassType

Get the job class type.

__index__()[source]

Return zero-based index for Python array indexing.

property priority: int

Get scheduling priority.

property deadline: float

Get relative deadline.

property completes: bool

Get whether this class completes a visit.

When completes=True (default), visiting this class contributes to the system response time. When completes=False, the class represents an intermediate step that doesn’t count towards completion.

property is_reference_class: bool

Get whether this class is the reference class for its chain.

When is_reference_class=True, this class’s visits at the reference station are used as the denominator for WN (residence time) computation. Typically set to True for the TASK class in LN layer models.

setReferenceClass(value)[source]

Set whether this class is the reference class for its chain (MATLAB-compatible name).

set_reference_class(value)[source]

Set whether this class is the reference class (snake_case alias).

isReferenceClass()[source]

Get whether this class is the reference class (MATLAB-compatible name).

property immediateFeedback: bool

Get whether immediate feedback is enabled globally for this class.

setImmediateFeedback(value)[source]

Set immediate feedback for this class (MATLAB-compatible name).

hasImmediateFeedback()[source]

Check if immediate feedback is enabled for this class.

set_immediate_feedback(value)

Set immediate feedback for this class (MATLAB-compatible name).

has_immediate_feedback()

Check if immediate feedback is enabled for this class.

set_reference_station(station)[source]

Set reference station for this class.

Parameters:

station – Reference Station node

get_reference_station()[source]

Get reference station.

is_reference_station(node)[source]

Check if a node is the reference station.

set_patience(*args)[source]

Set the class-level patience (impatience) distribution.

Mirrors MATLAB JobClass.setPatience and Java JobClass.setPatience:

  • set_patience(distribution): defaults the impatience type to RENEGING.

  • set_patience(impatience_type, distribution): sets both.

A node-scoped patience set with Queue.set_patience(jobclass, ...) takes precedence over the class-level one.

Parameters:
  • impatience_type – ImpatienceType (RENEGING or BALKING). The legacy strings ‘reneging’/’balking’ are also accepted.

  • distribution – Patience distribution.

get_patience()[source]

Get patience distribution (if any).

get_impatience_type()[source]

Get the class-level ImpatienceType (or None if no patience is set).

has_patience()[source]

Check if class has patience.

set_reply_signal_class(reply_class)[source]

Set reply signal class for synchronous calls.

get_reply_signal_class()[source]

Get reply signal class.

set_spawn_class(spawn_class)[source]

Set the class injected at the same station on each service completion of this class (LQN phase-2 continuation).

get_spawn_class()[source]

Get the spawn-on-completion class.

setPriority(value)[source]

Set scheduling priority .

getDeadline()[source]

Get relative deadline .

setDeadline(value)[source]

Set relative deadline .

getCompletes()[source]

Get whether this class completes a visit .

setCompletes(value)[source]

Set whether this class completes a visit .

setNumberOfJobs(njobs)[source]

Set the class population; only meaningful for closed classes.

set_number_of_jobs(njobs)

Set the class population; only meaningful for closed classes.

setReferenceStation(station)[source]

Alias for set_reference_station (CamelCase).

getReferenceStation()[source]

Alias for get_reference_station (CamelCase).

isReferenceStation(station)[source]

Alias for is_reference_station (CamelCase).

setPatience(*args)[source]

Alias for set_patience (CamelCase).

Accepts setPatience(distribution) or setPatience(impatience_type, distribution). It previously forwarded a single argument into the two-argument-only set_patience, so every call raised TypeError.

getPatience()[source]

Alias for get_patience (CamelCase).

getImpatienceType()[source]

Alias for get_impatience_type (CamelCase).

hasPatience()[source]

Alias for has_patience (CamelCase).

setReplySignalClass(class_obj)[source]

Alias for set_reply_signal_class (CamelCase).

getReplySignalClass()[source]

Alias for get_reply_signal_class (CamelCase).

set_priority(value)

Set scheduling priority .

get_deadline()

Get relative deadline .

set_deadline(value)

Set relative deadline .

get_completes()

Get whether this class completes a visit .

set_completes(value)

Set whether this class completes a visit .

class OpenClass(model, name, prio=0, deadline=float('inf'))[source]

Bases: JobClass

Open job class for external arrivals.

Jobs in an open class arrive from outside the system according to an arrival process and leave the system after completing service.

Parameters:
  • model (Network) – Parent network model.

  • name (str) – Name of the job class.

  • prio (int) – Priority level (default: 0).

  • deadline (float) – Soft deadline for response time (default: inf).

Initialize a job class.

Supports two signatures for compatibility: 1. (model, name, JobClassType, priority) - from classes.py 2. (jobclass_type, name, priority, deadline) - native implementation

Parameters:
  • model_or_type – Model instance or JobClassType

  • name_or_jobclass_type – Class name or JobClassType

  • jobclass_type_or_prio – JobClassType or priority

  • prio_or_deadline – Priority or deadline

property completes: bool

Whether jobs complete counting towards system throughput.

setCompletes(value)[source]

Set whether jobs complete counting towards system throughput.

getCompletes()[source]

Get whether jobs complete counting towards system throughput.

getDeadline()[source]

Get the soft deadline for this class.

setDeadline(deadline)[source]

Set the soft deadline for this class.

set_completes(value)

Set whether jobs complete counting towards system throughput.

get_completes()

Get whether jobs complete counting towards system throughput.

get_deadline()

Get the soft deadline for this class.

set_deadline(deadline)

Set the soft deadline for this class.

class ClosedClass(model, name, njobs, refstat, prio=0, deadline=float('inf'))[source]

Bases: JobClass

Closed job class with fixed population.

Jobs in a closed class circulate within the system with a fixed population. Jobs never leave the system but cycle through stations.

Parameters:
  • model (Network) – Parent network model.

  • name (str) – Name of the job class.

  • njobs (int) – Number of jobs (population) in this class.

  • refstat (Station) – Reference station for this class.

  • prio (int) – Priority level (default: 0).

  • deadline (float) – Soft deadline for response time (default: inf).

Initialize a job class.

Supports two signatures for compatibility: 1. (model, name, JobClassType, priority) - from classes.py 2. (jobclass_type, name, priority, deadline) - native implementation

Parameters:
  • model_or_type – Model instance or JobClassType

  • name_or_jobclass_type – Class name or JobClassType

  • jobclass_type_or_prio – JobClassType or priority

  • prio_or_deadline – Priority or deadline

setNumberOfJobs(njobs)[source]

Set the population of this closed class.

property completes: bool

Whether jobs complete counting towards system throughput.

setCompletes(value)[source]

Set whether jobs complete counting towards system throughput.

getCompletes()[source]

Get whether jobs complete counting towards system throughput.

getDeadline()[source]

Get the soft deadline for this class.

setDeadline(deadline)[source]

Set the soft deadline for this class.

set_number_of_jobs(njobs)

Set the population of this closed class.

property population: int

Get the population (alias for getNumberOfJobs).

property number_of_jobs: int

Get the population of this closed class.

set_completes(value)

Set whether jobs complete counting towards system throughput.

get_completes()

Get whether jobs complete counting towards system throughput.

get_deadline()

Get the soft deadline for this class.

set_deadline(deadline)

Set the soft deadline for this class.

class SelfLoopingClass(model, name, njobs, refstat, prio=0)[source]

Bases: ClosedClass

Self-looping closed class.

Jobs in this class perpetually loop at their reference station, useful for modeling background workloads or special scheduling.

Parameters:
  • model (Network) – Parent network model.

  • name (str) – Name of the job class.

  • njobs (int) – Number of jobs in this class.

  • refstat (Station) – Reference station where jobs loop.

  • prio (int) – Priority level (default: 0).

Initialize a job class.

Supports two signatures for compatibility: 1. (model, name, JobClassType, priority) - from classes.py 2. (jobclass_type, name, priority, deadline) - native implementation

Parameters:
  • model_or_type – Model instance or JobClassType

  • name_or_jobclass_type – Class name or JobClassType

  • jobclass_type_or_prio – JobClassType or priority

  • prio_or_deadline – Priority or deadline

Routing and Structure

class RoutingMatrix(network)[source]

Bases: object

Matrix representing routing probabilities between network nodes.

The routing matrix defines how jobs move between nodes in the network, specifying the probability that a job leaving one node will arrive at another node.

This is a pure Python implementation that stores routing data in numpy arrays and can be converted to Java when needed.

Parameters:

network (Network) – The parent network this routing matrix belongs to.

Initialize a routing matrix for a network.

Parameters:

network (Network) – The parent network.

__init__(network)[source]

Initialize a routing matrix for a network.

Parameters:

network (Network) – The parent network.

set(*args)[source]

Set routing probabilities in the matrix.

Supports multiple argument patterns: - 5 args: set(class_source, class_dest, node_source, node_dest, probability) - 3 args: set(class_source, class_dest, routing_matrix) - 2 args: set(jobclass, routing_matrix)

Returns:

Self for method chaining.

Return type:

RoutingMatrix

__getitem__(index)[source]

Enable [i][j] access to routing probabilities by node index.

Parameters:

index (int) – Row index (source node index).

Returns:

RoutingMatrixRowView for second-level indexing.

Return type:

RoutingMatrixRowView

__setitem__(key, value)[source]

Set routing using indexing notation.

Parameters:
  • key – Single jobclass (or int index) or tuple of (source_class, dest_class).

  • value – 2D numpy array of routing probabilities.

addClassSwitch(source_class, dest_class, source_node, dest_node, probability)[source]

Add a class switching route between nodes.

Parameters:
  • source_class (JobClass) – The job class before the switch.

  • dest_class (JobClass) – The job class after the switch.

  • source_node (Node) – The node where the job departs from.

  • dest_node (Node) – The node where the job arrives.

  • probability (float) – The probability of taking this route.

toMatrix()[source]

Convert the routing to a dense matrix.

Non-station nodes (like Router, ClassSwitch) are absorbed by computing transitive routing through them.

Returns:

(M*K) x (M*K) routing matrix indexed by station then class.

Return type:

ndarray

set_routing_matrix(jobclass, nodes, pmatrix)

Set routing probabilities using a matrix for specific job class(es).

Parameters:
  • jobclass (JobClass | List[JobClass]) – Job class or list of job classes.

  • nodes (List[Node]) – List of nodes in the routing matrix.

  • pmatrix (numpy.ndarray) – 2D or 3D matrix of routing probabilities.

add_route(jobclass, *args)

Add a routing path through multiple nodes for a job class.

Parameters:
  • jobclass (JobClass) – Job class to configure routing for.

  • *args – Nodes followed by optional probability. If last arg is a number, it’s used as probability.

add_class_switch(source_class, dest_class, source_node, dest_node, probability)

Add a class switching route between nodes.

Parameters:
  • source_class (JobClass) – The job class before the switch.

  • dest_class (JobClass) – The job class after the switch.

  • source_node (Node) – The node where the job departs from.

  • dest_node (Node) – The node where the job arrives.

  • probability (float) – The probability of taking this route.

State Representation

class State(network=None)[source]

Bases: object

State representation for stochastic network models.

Represents the system state including job populations at each node, phase information for multi-phase processes, and other state variables.

Initialize a state for the network.

Parameters:

network (Network | None) – The network this state belongs to.

__init__(network=None)[source]

Initialize a state for the network.

Parameters:

network (Network | None) – The network this state belongs to.

get(stateful_idx)[source]

Get state for a stateful node.

set(stateful_idx, state)[source]

Set state for a stateful node.

toArray()[source]

Convert to a flat array representation.

static fromMarginalBounds(model, node_idx, lb, ub, cap=None)[source]

Generate all valid states whose per-class marginal lies between lb and ub (inclusive), subject to the node capacity cap.

Parameters:
  • model (Network) – Network model (or NetworkStruct).

  • node_idx (int) – Node index (0-based).

  • lb – Lower bound on the number of resident jobs (scalar total or per-class vector). None is treated as all-zero.

  • ub – Upper bound on the number of resident jobs (scalar total or per-class vector).

  • cap – Total capacity at the node (defaults to the station’s total capacity, or infinity if unbounded).

Returns:

State space matrix where each row is a valid state.

Return type:

numpy.ndarray

References

MATLAB: matlab/src/lang/+State/fromMarginalBounds.m

static from_marginal(model, node_idx, n)

Generate state space with specific marginal job counts at a node.

Creates all possible network states where the specified node has exactly n[r] jobs of class r.

Parameters:
Returns:

State space matrix where each row is a valid state.

Return type:

numpy.ndarray

static from_marginal_and_running(model, node_idx, n, s)

Generate state space with specific marginal and running job counts.

Creates states where node has n[r] jobs of class r total, with s[r] jobs of class r currently in service (running).

Parameters:
Returns:

State space matrix where each row is a valid state.

Return type:

numpy.ndarray

static from_marginal_and_started(model, node_idx, n, s)

Generate state space with specific marginal and started job counts.

Creates states where node has n[r] jobs of class r total, with s[r] jobs of class r that have started service.

Parameters:
Returns:

State space matrix where each row is a valid state.

Return type:

numpy.ndarray

static to_marginal(model, node_idx, state_i)

Extract marginal job statistics from a state for a specific node.

Parameters:
  • model (Network) – Network model (or NetworkStruct).

  • node_idx (int) – Node index (0-based).

  • state_i (numpy.ndarray) – State vector/matrix for the node.

Returns:

  • ni: total jobs in the node,

  • nir: total jobs per class,

  • sir: jobs in service per class,

  • kir: jobs in service per class and phase.

Return type:

Tuple (ni, nir, sir, kir)

References

MATLAB: matlab/src/lang/+State/toMarginal.m

static from_marginal_bounds(model, node_idx, lb, ub, cap=None)

Generate all valid states whose per-class marginal lies between lb and ub (inclusive), subject to the node capacity cap.

Parameters:
  • model (Network) – Network model (or NetworkStruct).

  • node_idx (int) – Node index (0-based).

  • lb – Lower bound on the number of resident jobs (scalar total or per-class vector). None is treated as all-zero.

  • ub – Upper bound on the number of resident jobs (scalar total or per-class vector).

  • cap – Total capacity at the node (defaults to the station’s total capacity, or infinity if unbounded).

Returns:

State space matrix where each row is a valid state.

Return type:

numpy.ndarray

References

MATLAB: matlab/src/lang/+State/fromMarginalBounds.m

static is_valid(model, n, s=None, options=None)

Validate a network state against capacity and scheduling constraints.

Parameters:
  • model (Network) – Network model (or NetworkStruct).

  • n (numpy.ndarray) – (nstations x nclasses) matrix of resident jobs per class.

  • s (numpy.ndarray) – (nstations x nclasses) matrix of running jobs per class (optional).

  • options – Unused; accepted for API compatibility.

Returns:

True if the state satisfies all capacity, server, disabled-process and chain-population constraints; False otherwise.

Return type:

bool

References

MATLAB: matlab/src/lang/+State/isValid.m

class Mode(transition, name, index)[source]

Bases: object

A firing mode for a Petri net transition.

Modes define how a transition can fire, including: - Enabling conditions (required tokens from input places) - Inhibiting conditions (blocking tokens in places) - Firing outcomes (tokens produced to output places) - Timing distribution for the firing delay

Initialize a Mode.

Parameters:
  • transition (Transition) – Parent Transition object

  • name (str) – Mode name

  • index (int) – 1-based index of this mode

__init__(transition, name, index)[source]

Initialize a Mode.

Parameters:
  • transition (Transition) – Parent Transition object

  • name (str) – Mode name

  • index (int) – 1-based index of this mode

property name: str

Get mode name.

property index: int

Get 1-based index (MATLAB compatibility).

__index__()[source]

Allow Mode to be used as an index (0-based for Python arrays).

__int__()[source]

Convert to int (1-based index).

Solvers (line_solver.solvers)

The solvers module provides various analytical and simulation-based solvers.

Distributions (line_solver.distributions)

The distributions module provides probability distributions for service and arrival processes.

Base Distribution Classes

class Distribution[source]

Bases: ABC

Base class for all probability distributions.

This class provides the common interface for all probability distributions in LINE, including service time distributions and inter-arrival time distributions.

Initialize a new distribution.

__init__()[source]

Initialize a new distribution.

property name: str

Get the distribution name.

abstractmethod getMean()[source]

Get the mean (expected value) of the distribution.

abstractmethod getVar()[source]

Get the variance of the distribution.

get_mean()[source]

Get the mean (expected value) of the distribution.

get_var()[source]

Get the variance of the distribution.

eval_pmf(x)[source]

Evaluate the probability mass function at point x (snake_case alias for evalPMF; dispatches to the concrete distribution’s override).

getSCV()[source]

Get the squared coefficient of variation (SCV).

SCV = Var[X] / E[X]^2

getRate()[source]

Get the rate parameter (1/mean).

For immediate (zero-mean) distributions, returns GlobalConstants.Immediate (a large but finite value) to avoid numerical issues with infinite rates. This matches MATLAB’s behavior.

getSkew()[source]

Get the skewness of the distribution.

getSupport()[source]

Get the support range [min, max] of the distribution.

isContinuous()[source]

Check if this distribution is continuous.

isDiscrete()[source]

Check if this distribution is discrete.

isDisabled()[source]

Check if this distribution is equivalent to a Disabled distribution.

Mirrors MATLAB Distribution.isDisabled (isnan(getMean(self))): a distribution whose mean is not a number carries no usable process representation, so the struct records it as disabled rather than mislabelling it. Returning a hardcoded False, as this did, made refreshStruct treat such a distribution as an ordinary one.

isImmediate()[source]

Check if this distribution represents immediate service.

evalCDF(x)[source]

Evaluate the cumulative distribution function at point x.

evalPDF(x)[source]

Evaluate the probability density function at point x.

sample(n=1, rng=None)[source]

Generate random samples from this distribution.

Parameters:
Returns:

Array of n random samples.

Return type:

numpy.ndarray

get_scv()

Get the squared coefficient of variation (SCV).

SCV = Var[X] / E[X]^2

get_rate()

Get the rate parameter (1/mean).

For immediate (zero-mean) distributions, returns GlobalConstants.Immediate (a large but finite value) to avoid numerical issues with infinite rates. This matches MATLAB’s behavior.

get_skew()

Get the skewness of the distribution.

get_support()

Get the support range [min, max] of the distribution.

class ContinuousDistribution[source]

Bases: Distribution

Base class for continuous probability distributions.

Initialize a new distribution.

isContinuous()[source]

Check if this distribution is continuous.

isDiscrete()[source]

Check if this distribution is discrete.

evalLST(s)[source]

Laplace-Stieltjes transform E[e^{-sX}] evaluated at s.

Generic numerical fallback: rectangle-rule integration of evalPDF over [0, 20*mean] with 1000 points. Subclasses with a closed form or a MATLAB-matching numerical scheme (Pareto/Lognormal/Weibull) override this. Used by the G/M/1 MVA solver’s sigma-root for non-PH arrivals.

evalLaplaceTransform(s)

Laplace-Stieltjes transform E[e^{-sX}] evaluated at s.

Generic numerical fallback: rectangle-rule integration of evalPDF over [0, 20*mean] with 1000 points. Subclasses with a closed form or a MATLAB-matching numerical scheme (Pareto/Lognormal/Weibull) override this. Used by the G/M/1 MVA solver’s sigma-root for non-PH arrivals.

class DiscreteDistribution[source]

Bases: Distribution

Base class for discrete probability distributions.

Initialize a new distribution.

isContinuous()[source]

Check if this distribution is continuous.

isDiscrete()[source]

Check if this distribution is discrete.

evalPMF(x)[source]

Evaluate the probability mass function at point x.

class Markovian[source]

Bases: Distribution

Base class for Markovian (phase-type) distributions.

Markovian distributions can be represented in terms of initial probability vectors and transition rate matrices.

Initialize a new distribution.

getD0()[source]

Get the D0 matrix (for MAP representations).

getD1()[source]

Get the D1 matrix (for MAP representations).

getMu()[source]

Get the service rates in each phase.

getPhi()[source]

Get the completion probabilities from each phase.

getInitProb()[source]

Get the initial probability vector.

getNumberOfPhases()[source]

Get the number of phases.

getRepresentation()[source]

Return the (D0, D1) matrix representation used in the theory of Markovian arrival processes, as a list [D0, D1] (element k corresponds to matrix D_k).

get_representation()[source]

snake_case alias for getRepresentation().

getPH()[source]

Return the phase-type representation as a dict {0: D0, 1: D1}, matching the JAR Map<Integer, Matrix> shape.

get_ph()

Return the phase-type representation as a dict {0: D0, 1: D1}, matching the JAR Map<Integer, Matrix> shape.

get_d0()

Get the D0 matrix (for MAP representations).

get_d1()

Get the D1 matrix (for MAP representations).

get_mu()

Get the service rates in each phase.

get_phi()

Get the completion probabilities from each phase.

get_init_prob()

Get the initial probability vector.

get_number_of_phases()

Get the number of phases.

Continuous Distributions

class Exp(rate)[source]

Bases: ContinuousDistribution, Markovian

Exponential distribution.

The exponential distribution is the simplest continuous distribution for modeling service times in queueing systems. It has the memoryless property and SCV = 1.

Parameters:

rate (float) – The rate parameter (lambda = 1/mean).

Initialize a new distribution.

classmethod fit_mean(mean)[source]

Create an exponential distribution with the given mean.

Parameters:

mean (float) – Target mean.

Returns:

Exp distribution with rate = 1/mean.

Return type:

Exp

classmethod fitMean(mean)

Create an exponential distribution with the given mean.

Parameters:

mean (float) – Target mean.

Returns:

Exp distribution with rate = 1/mean.

Return type:

Exp

property rate: float

Get the rate parameter.

getMean()[source]

Get the mean (1/rate).

getVar()[source]

Get the variance (1/rate^2).

getSCV()[source]

Get the squared coefficient of variation (always 1 for exponential).

getSkew()[source]

Get the skewness (always 2 for exponential).

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

getNumberOfPhases()[source]

Get the number of phases (1 for exponential).

getD0()[source]

Get the D0 matrix for MAP representation.

getD1()[source]

Get the D1 matrix for MAP representation.

getMu()[source]

Get the service rates in each phase.

getPhi()[source]

Get the completion probabilities from each phase.

getInitProb()[source]

Get the initial probability vector.

classmethod fitRate(rate)[source]

Create an exponential distribution with the given rate.

Parameters:

rate (float) – The rate parameter (lambda).

Returns:

Exp distribution with specified rate.

Return type:

Exp

classmethod fit_rate(rate)

Create an exponential distribution with the given rate.

Parameters:

rate (float) – The rate parameter (lambda).

Returns:

Exp distribution with specified rate.

Return type:

Exp

get_rate()

Get the rate parameter (1/mean).

For immediate (zero-mean) distributions, returns GlobalConstants.Immediate (a large but finite value) to avoid numerical issues with infinite rates. This matches MATLAB’s behavior.

class Det(value)[source]

Bases: ContinuousDistribution

Deterministic (constant) distribution.

All service times are exactly equal to the specified value. Has SCV = 0 (no variability).

Parameters:

value (float) – The constant service time value.

Initialize a new distribution.

property value: float

Get the constant value.

getMean()[source]

Get the mean (equals the constant value).

getVar()[source]

Get the variance (always 0).

getSCV()[source]

Get the SCV (always 0).

getSkew()[source]

Get the skewness (undefined, return 0).

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x (delta function, return inf at value).

evalLST(s)[source]

LST of a deterministic time: exp(-s*t). Matches MATLAB Det.evalLST.

sample(n=1, rng=None)[source]

Generate random samples (all equal to value).

isImmediate()[source]

Check if this is an immediate (zero) service.

classmethod fit_mean(mean)[source]

Create a deterministic distribution with the given mean.

Since Det has zero variance, the mean equals the constant value.

Parameters:

mean (float) – The mean (and constant value) of the distribution.

Returns:

Det distribution with the specified mean.

Return type:

Det

classmethod fitMean(mean)

Create a deterministic distribution with the given mean.

Since Det has zero variance, the mean equals the constant value.

Parameters:

mean (float) – The mean (and constant value) of the distribution.

Returns:

Det distribution with the specified mean.

Return type:

Det

class Erlang(phase_rate, nphases)[source]

Bases: ContinuousDistribution, Markovian

Erlang distribution (sum of k exponentials).

The Erlang distribution is the distribution of the sum of k independent exponential random variables with the same rate. It has SCV = 1/k.

Parameters:
  • phase_rate (float) – Rate parameter for each exponential phase (alpha).

  • nphases (int) – Number of sequential exponential phases (r).

Mean = nphases / phase_rate = r / alpha

Initialize a new distribution.

classmethod fit_mean_and_scv(mean, scv)[source]

Create an Erlang distribution from mean and SCV.

For Erlang, SCV = 1/k where k is number of phases. So phases = round(1/SCV), constrained to be >= 1.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Erlang distribution with given mean and closest achievable SCV.

Return type:

Erlang

classmethod fit_mean_and_order(mean, phases)[source]

Create an Erlang distribution from mean and number of phases.

Parameters:
  • mean (float) – Target mean.

  • phases (int) – Number of phases (order).

Returns:

Erlang distribution with given mean and phases.

Return type:

Erlang

classmethod fitMeanAndScv(mean, scv)

Create an Erlang distribution from mean and SCV.

For Erlang, SCV = 1/k where k is number of phases. So phases = round(1/SCV), constrained to be >= 1.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Erlang distribution with given mean and closest achievable SCV.

Return type:

Erlang

classmethod fitMeanAndSCV(mean, scv)

Create an Erlang distribution from mean and SCV.

For Erlang, SCV = 1/k where k is number of phases. So phases = round(1/SCV), constrained to be >= 1.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Erlang distribution with given mean and closest achievable SCV.

Return type:

Erlang

classmethod fitMeanAndOrder(mean, phases)

Create an Erlang distribution from mean and number of phases.

Parameters:
  • mean (float) – Target mean.

  • phases (int) – Number of phases (order).

Returns:

Erlang distribution with given mean and phases.

Return type:

Erlang

property phases: int

Get the number of phases.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getSCV()[source]

Get the SCV (1/phases).

getSkew()[source]

Get the skewness.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

getNumberOfPhases()[source]

Get the number of phases.

getD0()[source]

Get the D0 matrix for MAP representation.

getD1()[source]

Get the D1 matrix for MAP representation.

getMu()[source]

Get the service rates in each phase.

getPhi()[source]

Get the completion probabilities from each phase.

getInitProb()[source]

Get the initial probability vector.

class Gamma(shape, scale)[source]

Bases: ContinuousDistribution

Gamma distribution.

The gamma distribution is a two-parameter continuous distribution that generalizes the exponential and Erlang distributions.

Parameters:
  • shape (float) – Shape parameter (k or alpha).

  • scale (float) – Scale parameter (theta).

Initialize a new distribution.

property shape: float

Get the shape parameter.

property scale: float

Get the scale parameter.

getMean()[source]

Get the mean (shape * scale).

getVar()[source]

Get the variance (shape * scale^2).

getSCV()[source]

Get the SCV (1/shape).

getSkew()[source]

Get the skewness.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

classmethod fit_mean_and_scv(mean, scv)[source]

Create a Gamma distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Gamma distribution with given mean and SCV.

Return type:

Gamma

classmethod fitMeanAndSCV(mean, scv)

Create a Gamma distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Gamma distribution with given mean and SCV.

Return type:

Gamma

classmethod fitMeanAndScv(mean, scv)

Create a Gamma distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Gamma distribution with given mean and SCV.

Return type:

Gamma

class HyperExp(p_or_probs, rate1_or_rates, rate2=None)[source]

Bases: ContinuousDistribution, Markovian

Hyperexponential distribution (mixture of exponentials).

The hyperexponential distribution is a mixture of exponential distributions. It has SCV >= 1.

Supports two calling conventions (matching MATLAB API):
  • HyperExp(p, rate1, rate2): 2-phase with probability p of rate1, probability (1-p) of rate2

  • HyperExp(probs, rates): n-phase with vectors of probabilities and rates

Parameters:
  • p_or_probs (float | list | numpy.ndarray) – For 2-phase: probability of first component (scalar). For n-phase: list/array of probabilities.

  • rate1_or_rates (float | list | numpy.ndarray) – For 2-phase: rate of first component (scalar). For n-phase: list/array of rates.

  • rate2 (float | None) – For 2-phase only: rate of second component.

Initialize a new distribution.

classmethod fit_mean_and_scv(mean, scv, p=0.99)[source]

Create a 2-phase hyperexponential distribution from mean and SCV.

Uses the same algorithm as MATLAB’s map_hyperexp function.

Parameters:
  • mean (float) – Target mean (MEAN).

  • scv (float) – Target squared coefficient of variation (must be >= 1).

  • p (float) – Probability of being served in phase 1 (default: 0.99).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

classmethod fit_mean_and_scv_balanced(mean, scv)[source]

Create a 2-phase hyperexponential distribution with balanced means.

Uses balanced means representation where p/mu1 = (1-p)/mu2.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation (must be >= 1).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

classmethod fitMeanAndScvBalanced(mean, scv)

Create a 2-phase hyperexponential distribution with balanced means.

Uses balanced means representation where p/mu1 = (1-p)/mu2.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation (must be >= 1).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

classmethod fitMeanAndSCVBalanced(mean, scv)

Create a 2-phase hyperexponential distribution with balanced means.

Uses balanced means representation where p/mu1 = (1-p)/mu2.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation (must be >= 1).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

classmethod fitMeanAndScv(mean, scv, p=0.99)

Create a 2-phase hyperexponential distribution from mean and SCV.

Uses the same algorithm as MATLAB’s map_hyperexp function.

Parameters:
  • mean (float) – Target mean (MEAN).

  • scv (float) – Target squared coefficient of variation (must be >= 1).

  • p (float) – Probability of being served in phase 1 (default: 0.99).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

classmethod fitMeanAndSCV(mean, scv, p=0.99)

Create a 2-phase hyperexponential distribution from mean and SCV.

Uses the same algorithm as MATLAB’s map_hyperexp function.

Parameters:
  • mean (float) – Target mean (MEAN).

  • scv (float) – Target squared coefficient of variation (must be >= 1).

  • p (float) – Probability of being served in phase 1 (default: 0.99).

Returns:

HyperExp distribution with given mean and SCV.

Return type:

HyperExp

property means: numpy.ndarray

Get the means of each component.

property probs: numpy.ndarray

Get the probabilities of each component.

property rates: numpy.ndarray

Get the rates of each component.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

getNumberOfPhases()[source]

Get the number of phases.

getD0()[source]

Get the D0 matrix for MAP representation.

getD1()[source]

Get the D1 matrix for MAP representation.

getMu()[source]

Get the service rates in each phase.

getPhi()[source]

Get the completion probabilities from each phase.

getInitProb()[source]

Get the initial probability vector.

class Lognormal(mu, sigma)[source]

Bases: ContinuousDistribution

Lognormal distribution.

A random variable X has a lognormal distribution if log(X) is normally distributed.

Parameters:
  • mu (float) – Mean of the underlying normal distribution.

  • sigma (float) – Standard deviation of the underlying normal distribution.

Initialize a new distribution.

property mu: float

Get the mu parameter.

property sigma: float

Get the sigma parameter.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getSkew()[source]

Get the skewness.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

evalLST(s)[source]

Numerical LST (rectangle rule, n=1000) matching MATLAB Lognormal.evalLST.

sample(n=1, rng=None)[source]

Generate random samples.

classmethod fit_mean_and_scv(mean, scv)[source]

Construct a Lognormal from a target mean and squared coefficient of variation (SCV = variance/mean^2), converting to log-space (mu, sigma).

Port of MATLAB Lognormal.fitMeanAndSCV.

classmethod fitMeanAndSCV(mean, scv)

Construct a Lognormal from a target mean and squared coefficient of variation (SCV = variance/mean^2), converting to log-space (mu, sigma).

Port of MATLAB Lognormal.fitMeanAndSCV.

classmethod fitMeanAndScv(mean, scv)

Construct a Lognormal from a target mean and squared coefficient of variation (SCV = variance/mean^2), converting to log-space (mu, sigma).

Port of MATLAB Lognormal.fitMeanAndSCV.

class Pareto(alpha, scale)[source]

Bases: ContinuousDistribution

Pareto distribution.

The Pareto distribution is a power-law distribution often used to model heavy-tailed phenomena.

Parameters:
  • alpha (float) – Shape parameter (tail index).

  • scale (float) – Scale parameter (minimum value).

Initialize a new distribution.

property alpha: float

Get the alpha parameter.

property scale: float

Get the scale parameter.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getSupport()[source]

Get the support [scale, inf).

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

evalLST(s)[source]

Numerical LST (rectangle rule, n=1000) matching MATLAB Pareto.evalLST.

sample(n=1, rng=None)[source]

Generate random samples.

classmethod fit_mean_and_scv(mean, scv)[source]

Create a Pareto distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Pareto distribution with given mean and SCV.

Return type:

Pareto

Note

For Pareto with alpha > 2: mean = alpha * scale / (alpha - 1) var = scale^2 * alpha / ((alpha - 1)^2 * (alpha - 2)) scv = var / mean^2 = 1 / (alpha * (alpha - 2))

Solving for alpha: alpha = (1 + sqrt(1 + 4*scv)) / (2*scv) Then: scale = mean * (alpha - 1) / alpha

classmethod fitMeanAndSCV(mean, scv)

Create a Pareto distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Pareto distribution with given mean and SCV.

Return type:

Pareto

Note

For Pareto with alpha > 2: mean = alpha * scale / (alpha - 1) var = scale^2 * alpha / ((alpha - 1)^2 * (alpha - 2)) scv = var / mean^2 = 1 / (alpha * (alpha - 2))

Solving for alpha: alpha = (1 + sqrt(1 + 4*scv)) / (2*scv) Then: scale = mean * (alpha - 1) / alpha

classmethod fitMeanAndScv(mean, scv)

Create a Pareto distribution from mean and SCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Pareto distribution with given mean and SCV.

Return type:

Pareto

Note

For Pareto with alpha > 2: mean = alpha * scale / (alpha - 1) var = scale^2 * alpha / ((alpha - 1)^2 * (alpha - 2)) scv = var / mean^2 = 1 / (alpha * (alpha - 2))

Solving for alpha: alpha = (1 + sqrt(1 + 4*scv)) / (2*scv) Then: scale = mean * (alpha - 1) / alpha

class Uniform(min_val, max_val)[source]

Bases: ContinuousDistribution

Uniform distribution on [min, max].

Parameters:
  • min_val (float) – Minimum value.

  • max_val (float) – Maximum value.

Initialize a new distribution.

property min_val: float

Get the minimum value.

property max_val: float

Get the maximum value.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getSkew()[source]

Get the skewness (always 0 for uniform).

getSupport()[source]

Get the support [min, max].

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

evalLST(s)[source]

LST of Uniform[min,max]: (e^{-s*min}-e^{-s*max})/(s*(max-min)). Matches MATLAB.

sample(n=1, rng=None)[source]

Generate random samples.

class Weibull(shape, scale)[source]

Bases: ContinuousDistribution

Weibull distribution.

The Weibull distribution is commonly used in reliability engineering to model time to failure.

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

  • scale (float) – Scale parameter (lambda).

Initialize a new distribution.

property shape: float

Get the shape parameter.

property scale: float

Get the scale parameter.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

evalLST(s)[source]

Numerical LST (rectangle rule, n=1000) matching MATLAB Weibull.evalLST.

sample(n=1, rng=None)[source]

Generate random samples.

Phase-Type Distributions

class APH(alpha_or_mean=None, T_or_scv=1.0, skew=None, mean=None, scv=None)[source]

Bases: PH

Acyclic Phase-Type distribution.

An APH distribution is a phase-type distribution where the underlying Markov chain has an acyclic structure (upper triangular T).

Can be constructed in two ways: 1. From matrices: APH(alpha, T) - like PH 2. From moments: APH(mean, scv=1.0, skew=None) - moment matching

Args (matrix form):

alpha: Initial probability vector (1 x n). T: Sub-generator matrix (n x n).

Args (moment form):

mean: Target mean (must be a positive scalar). scv: Target squared coefficient of variation (default: 1.0). skew: Target skewness (optional, for 3-moment matching).

Initialize APH from matrices or moments.

__init__(alpha_or_mean=None, T_or_scv=1.0, skew=None, mean=None, scv=None)[source]

Initialize APH from matrices or moments.

classmethod fit_mean_and_scv(mean, scv)[source]

Create an APH distribution from mean and SCV.

Uses moment matching to construct an acyclic phase-type distribution with the specified mean and squared coefficient of variation.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

APH distribution with given mean and SCV.

Return type:

APH

classmethod fitMeanAndScv(mean, scv)

Create an APH distribution from mean and SCV.

Uses moment matching to construct an acyclic phase-type distribution with the specified mean and squared coefficient of variation.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

APH distribution with given mean and SCV.

Return type:

APH

classmethod fitMeanAndSCV(mean, scv)

Create an APH distribution from mean and SCV.

Uses moment matching to construct an acyclic phase-type distribution with the specified mean and squared coefficient of variation.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

APH distribution with given mean and SCV.

Return type:

APH

classmethod fit_central(mean, scv, skew=None)[source]

Create an APH distribution from central moments.

Uses moment matching to construct an acyclic phase-type distribution with the specified mean, SCV, and optionally skewness.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

  • skew (float) – Target skewness (optional).

Returns:

APH distribution with given moments.

Return type:

APH

classmethod fitCentral(mean, scv, skew=None)

Create an APH distribution from central moments.

Uses moment matching to construct an acyclic phase-type distribution with the specified mean, SCV, and optionally skewness.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

  • skew (float) – Target skewness (optional).

Returns:

APH distribution with given moments.

Return type:

APH

classmethod fit_raw_moments(m1, m2, m3)[source]

Create an APH distribution from the first three raw moments.

Parameters:
  • m1 (float) – First raw moment E[X].

  • m2 (float) – Second raw moment E[X^2].

  • m3 (float) – Third raw moment E[X^3].

Returns:

APH distribution matching the given raw moments.

Return type:

APH

References

MATLAB: matlab/src/lang/processes/APH.m (fitRawMoments)

classmethod fitRawMoments(m1, m2, m3)

Create an APH distribution from the first three raw moments.

Parameters:
  • m1 (float) – First raw moment E[X].

  • m2 (float) – Second raw moment E[X^2].

  • m3 (float) – Third raw moment E[X^3].

Returns:

APH distribution matching the given raw moments.

Return type:

APH

References

MATLAB: matlab/src/lang/processes/APH.m (fitRawMoments)

class Coxian(means_or_rates, probs=None)[source]

Bases: PH

Coxian distribution.

A Coxian distribution is a special case of phase-type distributions where transitions can only go to the next phase or to absorption.

Parameters:
  • means_or_rates (list | numpy.ndarray) – Service rates (mu) for each phase. Rates are converted to means internally.

  • probs (list | numpy.ndarray | None) – Transition probabilities (phi). If length equals number of phases, the last element (which should be 1.0 for absorption) is dropped. If length is n-1, used as-is.

Initialize a new distribution.

property means: numpy.ndarray

Get the phase means.

property probs: numpy.ndarray

Get the continuation probabilities.

classmethod fit_mean_and_scv(mean, scv)[source]

Create a Coxian distribution from mean and SCV.

Uses moment matching to construct a Coxian distribution. Matches MATLAB Coxian.fitMeanAndSCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Coxian distribution with given mean and SCV.

Return type:

Coxian

classmethod fit_central(mean, scv, skew=None)[source]

Create a Coxian distribution from central moments.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

  • skew (float) – Target skewness (ignored, uses 2-moment matching).

Returns:

Coxian distribution with given moments.

Return type:

Coxian

classmethod fitMeanAndSCV(mean, scv)

Create a Coxian distribution from mean and SCV.

Uses moment matching to construct a Coxian distribution. Matches MATLAB Coxian.fitMeanAndSCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Coxian distribution with given mean and SCV.

Return type:

Coxian

classmethod fitMeanAndScv(mean, scv)

Create a Coxian distribution from mean and SCV.

Uses moment matching to construct a Coxian distribution. Matches MATLAB Coxian.fitMeanAndSCV.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Coxian distribution with given mean and SCV.

Return type:

Coxian

classmethod fitCentral(mean, scv, skew=None)

Create a Coxian distribution from central moments.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

  • skew (float) – Target skewness (ignored, uses 2-moment matching).

Returns:

Coxian distribution with given moments.

Return type:

Coxian

class Cox2(mu1, mu2, phi1)[source]

Bases: Coxian

2-phase Coxian distribution.

Convenience class for the common 2-phase case. Mirrors jline.lang.processes.Cox2 and MATLAB Cox2: the phases are given by their RATES, and phi1 is the COMPLETION probability of phase 1 (the job absorbs after phase 1 with probability phi1 and continues to phase 2 with probability 1 - phi1), matching Coxian’s phi convention.

Parameters:
  • mu1 (float) – Rate of phase 1.

  • mu2 (float) – Rate of phase 2.

  • phi1 (float) – Completion probability after phase 1.

Initialize a new distribution.

classmethod fit_mean_and_scv(mean, scv)[source]

Fit a 2-phase Coxian to a mean and SCV.

Port of jline.lang.processes.Cox2.fitMeanAndSCV and MATLAB Cox2.fitMeanAndSCV, which agree branch for branch.

This override is REQUIRED: Coxian.fit_mean_and_scv builds its result as cls(mu_list, phi_list), a signature Cox2 does not have, so the inherited classmethod raises TypeError on every call. It also may return an Erlang-like fit with more than two phases, which a Cox2 cannot represent.

A 2-phase Coxian cannot achieve SCV < 0.5; there phi1 comes out negative and the constructor rejects it. MATLAB and the JAR build the infeasible object silently instead.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Cox2 with the given mean and SCV.

Return type:

Cox2

classmethod fit_mean(mean)[source]

Fit a 2-phase Coxian to a mean alone.

Port of jline.lang.processes.Cox2.fitMean and MATLAB Cox2.fitMean.

classmethod fit_central(mean, var, skew=None)[source]

Fit a 2-phase Coxian to the first three central moments.

Port of jline.lang.processes.Cox2.fitCentral and MATLAB Cox2.fitCentral. This override is REQUIRED for a different reason than fit_mean_and_scv: Coxian.fit_central discards skew and forwards to a two-moment fit, so an inherited Cox2.fitCentral would silently ignore the third moment that the JAR and MATLAB fit exactly.

Falls back to a two-moment fit when the three-moment solution is infeasible, and to a mean-only fit when SCV < 0.5, as the JAR does.

Parameters:
  • mean (float) – Target mean.

  • var (float) – Target variance (NOT SCV – matches the JAR/MATLAB signature).

  • skew (float) – Target skewness. When omitted, reduces to a two-moment fit.

classmethod fitMeanAndSCV(mean, scv)

Fit a 2-phase Coxian to a mean and SCV.

Port of jline.lang.processes.Cox2.fitMeanAndSCV and MATLAB Cox2.fitMeanAndSCV, which agree branch for branch.

This override is REQUIRED: Coxian.fit_mean_and_scv builds its result as cls(mu_list, phi_list), a signature Cox2 does not have, so the inherited classmethod raises TypeError on every call. It also may return an Erlang-like fit with more than two phases, which a Cox2 cannot represent.

A 2-phase Coxian cannot achieve SCV < 0.5; there phi1 comes out negative and the constructor rejects it. MATLAB and the JAR build the infeasible object silently instead.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Cox2 with the given mean and SCV.

Return type:

Cox2

classmethod fitMeanAndScv(mean, scv)

Fit a 2-phase Coxian to a mean and SCV.

Port of jline.lang.processes.Cox2.fitMeanAndSCV and MATLAB Cox2.fitMeanAndSCV, which agree branch for branch.

This override is REQUIRED: Coxian.fit_mean_and_scv builds its result as cls(mu_list, phi_list), a signature Cox2 does not have, so the inherited classmethod raises TypeError on every call. It also may return an Erlang-like fit with more than two phases, which a Cox2 cannot represent.

A 2-phase Coxian cannot achieve SCV < 0.5; there phi1 comes out negative and the constructor rejects it. MATLAB and the JAR build the infeasible object silently instead.

Parameters:
  • mean (float) – Target mean.

  • scv (float) – Target squared coefficient of variation.

Returns:

Cox2 with the given mean and SCV.

Return type:

Cox2

classmethod fitMean(mean)

Fit a 2-phase Coxian to a mean alone.

Port of jline.lang.processes.Cox2.fitMean and MATLAB Cox2.fitMean.

classmethod fitCentral(mean, var, skew=None)

Fit a 2-phase Coxian to the first three central moments.

Port of jline.lang.processes.Cox2.fitCentral and MATLAB Cox2.fitCentral. This override is REQUIRED for a different reason than fit_mean_and_scv: Coxian.fit_central discards skew and forwards to a two-moment fit, so an inherited Cox2.fitCentral would silently ignore the third moment that the JAR and MATLAB fit exactly.

Falls back to a two-moment fit when the three-moment solution is infeasible, and to a mean-only fit when SCV < 0.5, as the JAR does.

Parameters:
  • mean (float) – Target mean.

  • var (float) – Target variance (NOT SCV – matches the JAR/MATLAB signature).

  • skew (float) – Target skewness. When omitted, reduces to a two-moment fit.

class PH(alpha, T)[source]

Bases: ContinuousDistribution, Markovian

Phase-type distribution.

A phase-type distribution is defined by an initial probability vector alpha and a sub-generator matrix T. The distribution represents the time until absorption in a continuous-time Markov chain.

Parameters:
  • alpha (list | numpy.ndarray) – Initial probability vector (1 x n).

  • T (list | numpy.ndarray) – Sub-generator matrix (n x n). Must have negative diagonal and non-negative off-diagonal elements.

Initialize a new distribution.

property alpha: numpy.ndarray

Get the initial probability vector.

property T: numpy.ndarray

Get the sub-generator matrix.

property t: numpy.ndarray

Get the exit rate vector.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getNumberOfPhases()[source]

Get the number of phases.

getD0()[source]

Get the D0 matrix (equals T).

getD1()[source]

Get the D1 matrix.

getMu()[source]

Get the service rates in each phase.

getPhi()[source]

Get the completion probabilities from each phase.

getInitProb()[source]

Get the initial probability vector.

evalCDF(x)[source]

Evaluate the CDF at point x.

evalPDF(x)[source]

Evaluate the PDF at point x.

sample(n=1, rng=None)[source]

Generate random samples using simulation.

Markovian Arrival Processes

class MAP(D0, D1)[source]

Bases: ContinuousDistribution, Markovian

Markovian Arrival Process.

A MAP is a generalization of the Poisson process that can capture correlation between inter-arrival times. It is defined by two matrices D0 and D1 where: - D0 contains transition rates without arrivals - D1 contains transition rates with arrivals - D0 + D1 is a valid generator matrix

Parameters:

Initialize a new distribution.

property D0: numpy.ndarray

Get the D0 matrix.

property D1: numpy.ndarray

Get the D1 matrix.

property pi: numpy.ndarray

Get the stationary distribution.

getD0()[source]

Get the D0 matrix.

getD1()[source]

Get the D1 matrix.

toTimeReversed()[source]

Return the time-reversed MAP.

Useful in departure-process and reversed-time arguments.

References

api/mam/map_analysis.py (map_timereverse)

to_time_reversed()[source]

snake_case alias for toTimeReversed().

getACF(lags=1)[source]

Return the autocorrelation coefficients of the inter-arrival times at the requested lag(s).

References

api/mam/map_analysis.py (map_acf)

get_acf(lags=1)[source]

snake_case alias for getACF().

getIDC()[source]

Return the asymptotic index of dispersion for counts (IDC).

References

api/mam/map_analysis.py (map_idc)

get_idc()[source]

snake_case alias for getIDC().

getMean()[source]

Get the mean inter-arrival time.

getVar()[source]

Get the variance of inter-arrival times.

getNumberOfPhases()[source]

Get the number of phases.

getMu()[source]

Get the total outgoing rate from each phase.

mu_i = -D0(i,i), matching MATLAB Markovian.getMu. This is the rate at which phase i is left by ANY transition, not only by an arrival. Summing D1 instead counts only the arrival transitions, so the two agree only when D0 carries no off-diagonal mass – which is why every renewal PH-like MAP in the test suite hid the difference.

getPhi()[source]

Get the probability that a transition out of a phase is an arrival.

phi_i = (D1*e)_i / -D0(i,i), matching MATLAB Markovian.getPhi. It equals 1 only when every exit from phase i emits an arrival; a MAP with hidden phase changes has phi < 1. The D0(0,0) == 0 guard mirrors the MATLAB special case for an immediate process.

getInitProb()[source]

Get the phase distribution embedded at arrival instants.

This is map_pie, the equilibrium of the embedded DTMC P = (-D0)^(-1) D1, and it is the vector that governs the inter-arrival time marginal. It is NOT the time-stationary phase distribution self._pi, which is a different vector whenever the phase process is not symmetric in its arrival rates. Matches MATLAB Markovian.getInitProb, which calls map_pie, and agrees with RAP.getInitProb on a (D0,D1) pair that is both a MAP and a RAP.

getRate()[source]

Get the arrival rate (1/mean).

set_mean(target_mean)[source]

Create a new MAP with the specified mean by scaling rates.

The structure of the MAP is preserved, only the rates are scaled to achieve the target mean.

Parameters:

target_mean (float) – Target mean inter-arrival/service time.

Returns:

New MAP with the specified mean.

Return type:

MAP

setMean(target_mean)

Create a new MAP with the specified mean by scaling rates.

The structure of the MAP is preserved, only the rates are scaled to achieve the target mean.

Parameters:

target_mean (float) – Target mean inter-arrival/service time.

Returns:

New MAP with the specified mean.

Return type:

MAP

sample(n=1, rng=None)[source]

Generate random inter-arrival times.

classmethod rand(n=2, seed=None)[source]

Create a random MAP with n phases.

Generates a random MAP with the specified number of phases. The D0 and D1 matrices are randomly generated to form a valid MAP.

Parameters:
  • n (int) – Number of phases (default: 2).

  • seed (int) – Random seed for reproducibility (optional).

Returns:

MAP distribution with random parameters.

Return type:

MAP

class MMPP2(lambda0, lambda1, sigma0, sigma1)[source]

Bases: MAP

Markov-Modulated Poisson Process with 2 states.

A special case of MAP with two states, where arrivals occur according to Poisson processes with rates lambda0 and lambda1, and the modulating chain switches between states with rates sigma0 and sigma1.

Parameters:
  • lambda0 (float) – Arrival rate in state 0.

  • lambda1 (float) – Arrival rate in state 1.

  • sigma0 (float) – Transition rate from state 0 to state 1.

  • sigma1 (float) – Transition rate from state 1 to state 0.

Initialize a new distribution.

property lambda0: float

Get arrival rate in state 0.

property lambda1: float

Get arrival rate in state 1.

property sigma0: float

Get transition rate from state 0 to 1.

property sigma1: float

Get transition rate from state 1 to 0.

getIDC()[source]

Get the Index of Dispersion for Counts.

get_idc()[source]

Index of Dispersion for Counts (snake_case alias for getIDC).

static fit_mean_scv_acf(mean, scv, acf_decay)[source]

Fit MMPP2 to match mean, SCV, and ACF decay.

Parameters:
  • mean (float) – Target mean inter-arrival time.

  • scv (float) – Target squared coefficient of variation.

  • acf_decay (float) – ACF decay parameter (gamma2).

Returns:

Fitted MMPP2 distribution.

Return type:

MMPP2

Discrete Distributions

class Bernoulli(p)[source]

Bases: DiscreteDistribution

Bernoulli distribution.

The simplest discrete distribution with two outcomes: success (1) with probability p and failure (0) with probability 1-p.

Parameters:

p (float) – Probability of success (0 <= p <= 1).

Initialize a new distribution.

property p: float

Get the probability of success.

getMean()[source]

Get the mean (equals p).

getVar()[source]

Get the variance (p * (1 - p)).

getSkew()[source]

Get the skewness.

getSupport()[source]

Get the support {0, 1}.

evalPMF(x)[source]

Evaluate the PMF at point x.

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

class Binomial(n, p)[source]

Bases: DiscreteDistribution

Binomial distribution.

The binomial distribution models the number of successes in n independent Bernoulli trials.

Parameters:
  • n (int) – Number of trials.

  • p (float) – Probability of success on each trial.

Initialize a new distribution.

property n: int

Get the number of trials.

property p: float

Get the probability of success.

getMean()[source]

Get the mean (n * p).

getVar()[source]

Get the variance (n * p * (1 - p)).

getSkew()[source]

Get the skewness.

getSupport()[source]

Get the support [0, n].

evalPMF(x)[source]

Evaluate the PMF at point x.

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

class DiscreteUniform(a, b)[source]

Bases: DiscreteDistribution

Discrete Uniform distribution.

Assigns equal probability to all integers in [a, b].

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

  • b (int) – Upper bound (inclusive).

Initialize a new distribution.

property a: int

Get the lower bound.

property b: int

Get the upper bound.

getMean()[source]

Get the mean ((a + b) / 2).

getVar()[source]

Get the variance ((n^2 - 1) / 12).

getSkew()[source]

Get the skewness (0 for symmetric distribution).

getSupport()[source]

Get the support [a, b].

evalPMF(x)[source]

Evaluate the PMF at point x.

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

class Geometric(p)[source]

Bases: DiscreteDistribution

Geometric distribution.

The geometric distribution models the number of failures before the first success in a sequence of Bernoulli trials.

Parameters:

p (float) – Probability of success on each trial (0 < p <= 1).

Initialize a new distribution.

property p: float

Get the probability of success.

getMean()[source]

Get the mean (1/p for number of trials).

getVar()[source]

Get the variance.

getSkew()[source]

Get the skewness.

getSupport()[source]

Get the support [1, inf).

evalPMF(x)[source]

Evaluate the PMF at point x (number of trials until first success).

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

class Poisson(lambda_)[source]

Bases: DiscreteDistribution

Poisson distribution.

The Poisson distribution models the number of events occurring in a fixed interval of time or space.

Parameters:

lambda – Rate parameter (mean = variance = lambda).

Initialize a new distribution.

property lambda_: float

Get the rate parameter.

getMean()[source]

Get the mean (equals lambda).

getVar()[source]

Get the variance (equals lambda).

getSCV()[source]

Get the SCV (1/lambda).

getSkew()[source]

Get the skewness.

getSupport()[source]

Get the support [0, inf).

evalPMF(x)[source]

Evaluate the probability mass function at point x.

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples.

class Zipf(s, n=10000)[source]

Bases: DiscreteDistribution

Zipf distribution.

The Zipf distribution is a power-law distribution often used to model rank-frequency relationships (e.g., word frequencies).

Parameters:
  • s (float) – Shape parameter (s > 0).

  • n (int) – Upper bound on support (optional, defaults to large value).

Initialize a new distribution.

property s: float

Get the shape parameter.

property n: int

Get the upper bound.

getMean()[source]

Get the mean.

getVar()[source]

Get the variance.

getSupport()[source]

Get the support [1, n].

evalPMF(x)[source]

Evaluate the PMF at point x.

evalCDF(x)[source]

Evaluate the CDF at point x.

sample(n=1, rng=None)[source]

Generate random samples using inverse transform.

Special Distributions

class Disabled[source]

Bases: ContinuousDistribution

Disabled distribution.

Represents a disabled service (no service at all). Used for nodes that don’t serve a particular job class.

Initialize a new distribution.

classmethod getInstance()[source]

Get singleton instance of Disabled distribution.

classmethod get_instance()

Get singleton instance of Disabled distribution.

getMean()[source]

Get the mean (infinity for disabled).

getVar()[source]

Get the variance.

isDisabled()[source]

Check if this distribution is disabled.

class Immediate[source]

Bases: Det

Immediate (zero delay) distribution.

Represents instantaneous service with zero delay.

Initialize a new distribution.

classmethod getInstance()[source]

Get singleton instance of Immediate distribution.

classmethod get_instance()

Get singleton instance of Immediate distribution.

isImmediate()[source]

Check if this is immediate service.

class Replayer(trace, loop=True)[source]

Bases: DiscreteDistribution

Trace-based distribution that replays recorded values.

Used for simulation where inter-arrival or service times are read from a trace file or data array.

Parameters:
  • trace (str | list | numpy.ndarray) – Array of values to replay.

  • loop (bool) – Whether to loop when trace is exhausted (default: True).

Initialize a new distribution.

property trace: numpy.ndarray

Get the trace data.

property loop: bool

Check if looping is enabled.

reset()[source]

Reset the replay index to the beginning.

getMean()[source]

Get the mean of the trace.

getVar()[source]

Get the variance of the trace.

getSkewness()[source]

Get the skewness of the trace.

getSupport()[source]

Get the support [min, max] of trace values.

evalPMF(x)[source]

Evaluate PMF based on trace frequency.

evalCDF(x)[source]

Evaluate CDF based on trace.

next_value()[source]

Get the next value in the trace.

sample(n=1, rng=None)[source]

Get the next n values from the trace.

fit_aph()[source]

Fit an acyclic phase-type (APH) distribution to the trace data.

Uses 3-moment matching (mean, SCV, skewness) to determine the optimal APH representation, matching MATLAB’s behavior.

Returns:

APH distribution fitted to the trace data.

Layered Networks (line_solver.layered)

The layered module provides support for layered queueing networks (LQNs).