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,ElementQueueing 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
- add_link(source, dest)[source]
Add a link between two nodes.
- Parameters:
- Raises:
ValueError – If nodes not in network
- add_links(routing_matrix)[source]
Add multiple links via routing matrix.
- Parameters:
routing_matrix (RoutingMatrix | numpy.ndarray) – RoutingMatrix or numpy array with probabilities
- add_link_list(*nodes)[source]
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:
- 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)
- init_routing_matrix()[source]
Initialize an empty routing matrix for all nodes and classes.
- Returns:
RoutingMatrix with zeros (no routing initially)
- Return type:
- 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.
- link(routing_matrix)[source]
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:
- 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:
- setLogPath(path)
Set the path for logger output files.
- Parameters:
path (str) – Directory path for log files
- link_and_log(P, is_node_logged, log_path=None)[source]
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.
- 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.
- get_connection_matrix()[source]
Get the network connection (adjacency) matrix.
- Returns:
(N x N) binary matrix where 1 indicates a connection
- Return type:
- 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 classrcan switch into classsat 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_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_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)
- 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:
- 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
- relink(routing_matrix)[source]
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
- 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:
- 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:
- 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:
- 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:
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.
- 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 classrcan switch into classsat 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.
- 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:
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:
Example
>>> model = Network('MyModel') >>> # ... build model ... >>> model.jsimgView() # Opens in JMT graphical editor
References
- 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:
Example
>>> model = Network('MyModel') >>> # ... build model ... >>> model.jsimwView() # Opens in JMT wizard
References
- 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:
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:
References
- 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:
References
- 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:
References
- static cluster_ps(lambda_rates, D, S=None, dispatching=None)[source]
Open PS cluster (single-server queues unless S overrides multiplicity).
- 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:
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
- 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:
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:
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:
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:
- 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:
objectStatic 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:
NetworkElementAbstract 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.
- link(node_to)[source]
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_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.
- 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).
- class Source(model, name)[source]
Bases:
StationSource 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 isline_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
- 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.
- 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.
- 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 isline_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:
StationQueue 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.)
- 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)wheremuis a callable taking the ordered state vectorc(a list/array of class indices,c[0]the oldest job) and returning the scalar total service ratemu(c). Per-class service distributions are not used by an order-independent/PAS queue.
- 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_classincache’s retrieval system. The default (when not overridden) is the read class’s own service distribution at this queue.itemis 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_classincache’s retrieval system. The default (when not overridden) is the read class’s own service distribution at this queue.itemis 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.)
- 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.
- 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).
- 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.
- 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:
- 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
- set_hetero_sched_policy(policy)[source]
Set the heterogeneous scheduling policy.
- Parameters:
policy – HeteroSchedPolicy value
- 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:
- isHeterogeneous()
Check if this queue has heterogeneous servers.
- Returns:
True if server types have been defined
- Return type:
- 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:
- 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)
- 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
- getSetupTime(jobclass)
Get setup time distribution for a job class.
- getDelayOffTime(jobclass)
Get delay-off time distribution for a job class.
- 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)
- 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.
- 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, []).
- 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).
- 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)
- 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.
- 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:
QueueDelay 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:
NodeSink 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
- class Router(model, name)[source]
Bases:
NodeRouter 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
- class Fork(model, name)[source]
Bases:
NodeFork 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
- setStatePrior(prior)
Set Fork state prior (FJ tag-augmented copies only).
- set_tasks_per_link(ntasks)[source]
Set number of tasks spawned per outgoing link (experimental).
- Parameters:
ntasks (numpy.ndarray) – Array with task counts for each link
- class Join(model, name, fork=None)[source]
Bases:
StationJoin 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:
- set_strategy(jobclass, strategy)[source]
Set join strategy for a job class.
- Parameters:
jobclass (JobClass) – Job class
strategy (JoinStrategy) – Join strategy (STD, QUORUM, etc.)
- class Cache(model, name, num_items, item_level_cap, replacement_strategy=ReplacementStrategy.LRU)[source]
Bases:
StationMulti-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 item_level_cap: numpy.ndarray
Get the capacity array for each cache level.
- 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.
- 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.
- 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)
- 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.
- 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).
- 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).
- set_result_item_prob(item_prob)[source]
Set the per-item occupancy [items x (lists+1)]; col 0 = miss, cols 1.. = per-list.
- 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:
- get_capacity_vector()[source]
Get the cache capacity vector.
- Returns:
Array of cache level capacities
- Return type:
- property retrieval_system_capacity: int
Number of items that can be in the retrieval system simultaneously (0 when no retrieval system is configured).
- set_retrieval_class(input_class, output_class, item)[source]
Set the retrieval class for (item, input_class). item is 0-based.
- 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 withqueue.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).
- set_item_routing_probability(jobin_class, item, source, dest, probability)[source]
Probability of routing the retrieval class for
itembetween two nodes of the retrieval system.source/destare either a retrieval queue or the cache itself: pass the cache assourcefor a cache->queue entry, or asdestfor a queue->cache exit.itemis 0-based. Requires a priorset_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 withqueue.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).
- 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
itembetween two nodes of the retrieval system.source/destare either a retrieval queue or the cache itself: pass the cache assourcefor a cache->queue entry, or asdestfor a queue->cache exit.itemis 0-based. Requires a priorset_retrieval_system()call.
- set_item_routing_prob(jobin_class, item, source, dest, probability)
Probability of routing the retrieval class for
itembetween two nodes of the retrieval system.source/destare either a retrieval queue or the cache itself: pass the cache assourcefor a cache->queue entry, or asdestfor a queue->cache exit.itemis 0-based. Requires a priorset_retrieval_system()call.
- setItemRoutingProb(jobin_class, item, source, dest, probability)
Probability of routing the retrieval class for
itembetween two nodes of the retrieval system.source/destare either a retrieval queue or the cache itself: pass the cache assourcefor a cache->queue entry, or asdestfor a queue->cache exit.itemis 0-based. Requires a priorset_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
- class ClassSwitch(model, name, cs_matrix=None)[source]
Bases:
NodeClassSwitch 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:
StationPlace 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).
- 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_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:
StatefulNodeTransition 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
- set_enabling_conditions(mode, jobclass, input_node, enabling_condition)[source]
Set enabling conditions for a mode.
- 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.
- set_firing_outcome(mode, jobclass, output_node, firing_outcome)[source]
Set firing outcome for a mode.
- 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.)
- 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:
NetworkElementAbstract 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.
- 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).
- 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).
- 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
- set_patience(*args)[source]
Set the class-level patience (impatience) distribution.
Mirrors MATLAB
JobClass.setPatienceand JavaJobClass.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.
- 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).
- set_number_of_jobs(njobs)
Set the class population; only meaningful for closed classes.
- setPatience(*args)[source]
Alias for set_patience (CamelCase).
Accepts
setPatience(distribution)orsetPatience(impatience_type, distribution). It previously forwarded a single argument into the two-argument-only set_patience, so every call raised TypeError.
- 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:
JobClassOpen 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:
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
- 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:
JobClassClosed 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:
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
- set_number_of_jobs(njobs)
Set 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:
ClosedClassSelf-looping closed class.
Jobs in this class perpetually loop at their reference station, useful for modeling background workloads or special scheduling.
- Parameters:
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:
objectMatrix 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:
- __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.
- 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).
- 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.
State Representation
- class State(network=None)[source]
Bases:
objectState 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.
- static fromMarginalBounds(model, node_idx, lb, ub, cap=None)[source]
Generate all valid states whose per-class marginal lies between
lbandub(inclusive), subject to the node capacitycap.- 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).
Noneis 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:
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:
model (Network) – Network model
node_idx (int) – Node index (0-based)
n (List[int] | numpy.ndarray) – Vector of job counts per class
- Returns:
State space matrix where each row is a valid state.
- Return type:
- 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:
model (Network) – Network model
node_idx (int) – Node index (0-based)
n (List[int] | numpy.ndarray) – Vector of total job counts per class
s (List[int] | numpy.ndarray) – Vector of running job counts per class
- Returns:
State space matrix where each row is a valid state.
- Return type:
- 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:
model (Network) – Network model
node_idx (int) – Node index (0-based)
n (List[int] | numpy.ndarray) – Vector of total job counts per class
s (List[int] | numpy.ndarray) – Vector of started job counts per class
- Returns:
State space matrix where each row is a valid state.
- Return type:
- 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
lbandub(inclusive), subject to the node capacitycap.- 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).
Noneis 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:
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:
References
MATLAB: matlab/src/lang/+State/isValid.m
- class Mode(transition, name, index)[source]
Bases:
objectA 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
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:
ABCBase 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.
- eval_pmf(x)[source]
Evaluate the probability mass function at point x (snake_case alias for evalPMF; dispatches to the concrete distribution’s override).
- 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.
- 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.
- sample(n=1, rng=None)[source]
Generate random samples from this distribution.
- Parameters:
n (int) – Number of samples to generate.
rng (numpy.random.Generator | None) – Optional random number generator.
- Returns:
Array of n random samples.
- Return type:
- 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:
DistributionBase class for continuous probability distributions.
Initialize a new distribution.
- 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:
DistributionBase class for discrete probability distributions.
Initialize a new distribution.
- class Markovian[source]
Bases:
DistributionBase 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.
- getRepresentation()[source]
Return the
(D0, D1)matrix representation used in the theory of Markovian arrival processes, as a list[D0, D1](elementkcorresponds to matrixD_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,MarkovianExponential 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 fitMean(mean)
Create an exponential distribution with the given mean.
- classmethod fit_rate(rate)
Create an exponential distribution with the given rate.
- 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:
ContinuousDistributionDeterministic (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.
- class Erlang(phase_rate, nphases)[source]
Bases:
ContinuousDistribution,MarkovianErlang 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:
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.
- classmethod fit_mean_and_order(mean, phases)[source]
Create an Erlang distribution from mean and number of phases.
- 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.
- 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.
- classmethod fitMeanAndOrder(mean, phases)
Create an Erlang distribution from mean and number of phases.
- class Gamma(shape, scale)[source]
Bases:
ContinuousDistributionGamma distribution.
The gamma distribution is a two-parameter continuous distribution that generalizes the exponential and Erlang distributions.
Initialize a new distribution.
- classmethod fitMeanAndSCV(mean, scv)
Create a Gamma distribution from mean and SCV.
- class HyperExp(p_or_probs, rate1_or_rates, rate2=None)[source]
Bases:
ContinuousDistribution,MarkovianHyperexponential 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.
- 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.
- classmethod fitMeanAndScvBalanced(mean, scv)
Create a 2-phase hyperexponential distribution with balanced means.
Uses balanced means representation where p/mu1 = (1-p)/mu2.
- classmethod fitMeanAndSCVBalanced(mean, scv)
Create a 2-phase hyperexponential distribution with balanced means.
Uses balanced means representation where p/mu1 = (1-p)/mu2.
- 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.
- 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.
- 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.
- class Lognormal(mu, sigma)[source]
Bases:
ContinuousDistributionLognormal distribution.
A random variable X has a lognormal distribution if log(X) is normally distributed.
- Parameters:
Initialize a new distribution.
- 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:
ContinuousDistributionPareto distribution.
The Pareto distribution is a power-law distribution often used to model heavy-tailed phenomena.
- Parameters:
Initialize a new distribution.
- classmethod fit_mean_and_scv(mean, scv)[source]
Create a Pareto distribution from mean and SCV.
- Parameters:
- Returns:
Pareto distribution with given mean and SCV.
- Return type:
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:
- Returns:
Pareto distribution with given mean and SCV.
- Return type:
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:
- Returns:
Pareto distribution with given mean and SCV.
- Return type:
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:
ContinuousDistributionUniform distribution on [min, max].
Initialize a new distribution.
- class Weibull(shape, scale)[source]
Bases:
ContinuousDistributionWeibull distribution.
The Weibull distribution is commonly used in reliability engineering to model time to failure.
Initialize a new distribution.
Phase-Type Distributions
- class APH(alpha_or_mean=None, T_or_scv=1.0, skew=None, mean=None, scv=None)[source]
Bases:
PHAcyclic 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.
- 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.
- 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.
- 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.
- 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.
- classmethod fit_raw_moments(m1, m2, m3)[source]
Create an APH distribution from the first three raw moments.
- Parameters:
- Returns:
APH distribution matching the given raw moments.
- Return type:
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:
- Returns:
APH distribution matching the given raw moments.
- Return type:
References
MATLAB: matlab/src/lang/processes/APH.m (fitRawMoments)
- class Coxian(means_or_rates, probs=None)[source]
Bases:
PHCoxian 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.
- classmethod fit_central(mean, scv, skew=None)[source]
Create a Coxian distribution from central moments.
- classmethod fitMeanAndSCV(mean, scv)
Create a Coxian distribution from mean and SCV.
Uses moment matching to construct a Coxian distribution. Matches MATLAB Coxian.fitMeanAndSCV.
- classmethod fitMeanAndScv(mean, scv)
Create a Coxian distribution from mean and SCV.
Uses moment matching to construct a Coxian distribution. Matches MATLAB Coxian.fitMeanAndSCV.
- classmethod fitCentral(mean, scv, skew=None)
Create a Coxian distribution from central moments.
- class Cox2(mu1, mu2, phi1)[source]
Bases:
Coxian2-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:
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.
- 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.
- 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.
- 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.
- 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.
- class PH(alpha, T)[source]
Bases:
ContinuousDistribution,MarkovianPhase-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.
Markovian Arrival Processes
- class MAP(D0, D1)[source]
Bases:
ContinuousDistribution,MarkovianMarkovian 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:
D0 (list | numpy.ndarray) – Matrix of transition rates without arrivals.
D1 (list | numpy.ndarray) – Matrix of transition rates with arrivals.
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.
- 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)
- getIDC()[source]
Return the asymptotic index of dispersion for counts (IDC).
References
api/mam/map_analysis.py (map_idc)
- 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.
- 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.
- 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.
- class MMPP2(lambda0, lambda1, sigma0, sigma1)[source]
Bases:
MAPMarkov-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:
Initialize a new distribution.
Discrete Distributions
- class Bernoulli(p)[source]
Bases:
DiscreteDistributionBernoulli 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.
- class Binomial(n, p)[source]
Bases:
DiscreteDistributionBinomial distribution.
The binomial distribution models the number of successes in n independent Bernoulli trials.
Initialize a new distribution.
- class DiscreteUniform(a, b)[source]
Bases:
DiscreteDistributionDiscrete Uniform distribution.
Assigns equal probability to all integers in [a, b].
Initialize a new distribution.
- class Geometric(p)[source]
Bases:
DiscreteDistributionGeometric 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.
- class Poisson(lambda_)[source]
Bases:
DiscreteDistributionPoisson 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.
- class Zipf(s, n=10000)[source]
Bases:
DiscreteDistributionZipf distribution.
The Zipf distribution is a power-law distribution often used to model rank-frequency relationships (e.g., word frequencies).
- Parameters:
Initialize a new distribution.
Special Distributions
- class Disabled[source]
Bases:
ContinuousDistributionDisabled 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 get_instance()
Get singleton instance of Disabled distribution.
- class Immediate[source]
Bases:
DetImmediate (zero delay) distribution.
Represents instantaneous service with zero delay.
Initialize a new distribution.
- classmethod get_instance()
Get singleton instance of Immediate distribution.
- class Replayer(trace, loop=True)[source]
Bases:
DiscreteDistributionTrace-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.
Layered Networks (line_solver.layered)
The layered module provides support for layered queueing networks (LQNs).