API Documentation

This section provides detailed API documentation for all LINE Solver Python modules.

API Submodules

Stochastic Networks (line_solver.api.sn)

Service Network (SN) utilities.

Native Python implementations for stochastic network structure analysis, validation, and parameter extraction.

Key classes:

NetworkStruct: Data structure summarizing network characteristics SnGetDemandsResult: Result of sn_get_demands_chain calculation

Key functions:

sn_get_demands_chain: Aggregate class-level parameters into chain-level sn_has_*: Network property predicates sn_is_*: Model type checks sn_get_*: Parameter extraction sn_validate: Network validation

class MatrixArray(input_array)[source]

Bases: ndarray

Numpy array subclass with .get() and .set() methods for API compatibility.

This class provides compatibility with the wrapper mode that uses JLine’s Matrix class which has get(i, j) and set(i, j, value) methods.

Create MatrixArray from existing array.

__array_finalize__(obj)[source]

Handle view casting and new-from-template.

__getitem__(key)[source]

Override indexing to handle 2D indexing on 1D arrays.

This provides compatibility with MATLAB-style row/column vectors where a 1D array can be indexed as (0, j) or (i, 0).

static __new__(cls, input_array)[source]

Create MatrixArray from existing array.

__setitem__(key, value)[source]

Override item setting to handle 2D indexing on 1D arrays.

get(i, j=None)[source]

Get element at index (i, j) or just i if 1D.

Parameters:
  • i – Row index (or element index for 1D)

  • j – Column index (optional, for 2D arrays)

Returns:

Element value at the specified index

set(i, j, value=None)[source]

Set element at index (i, j) or just i if 1D.

Parameters:
  • i – Row index (or element index for 1D)

  • j – Column index or value (for 1D arrays)

  • value – Value to set (optional, for 2D arrays)

class NetworkStruct(nstations=0, nstateful=0, nnodes=0, nclasses=0, nchains=0, nclosedjobs=0, njobs=<factory>, nservers=<factory>, cap=None, classcap=None, rates=<factory>, scv=<factory>, phases=None, phasessz=None, phaseshift=None, visits=<factory>, nodevisits=<factory>, inchain=<factory>, chains=<factory>, refstat=<factory>, refclass=<factory>, sched=<factory>, schedparam=None, routing=<factory>, rt=None, rtnodes=None, nodetype=<factory>, isstation=<factory>, isstateful=<factory>, isstatedep=None, nodeToStation=<factory>, nodeToStateful=<factory>, stationToNode=<factory>, stationToStateful=<factory>, statefulToNode=<factory>, statefulToStation=<factory>, state=<factory>, stateprior=<factory>, space=<factory>, lldscaling=None, cdscaling=None, classprio=None, classdeadline=None, isslc=None, issignal=None, signaltype=None, syncreply=None, connmatrix=None, nodenames=<factory>, classnames=<factory>, mu=None, phi=None, proc=None, pie=None, procid=None, lst=None, fj=None, droprule=None, nregions=0, region=None, regionrule=None, regionweight=None, regionsz=None, sync=None, gsync=None, nodeparam=None, reward=None, rtorig=None, csmask=None, nvars=None)[source]

Bases: object

Data structure summarizing network characteristics.

This class is the Python equivalent in native Python. It contains all parameters needed by solvers to analyze a queueing network.

nstations

Number of stations (queues, delays, sources, joins, places)

Type:

int

nstateful

Number of stateful nodes

Type:

int

nnodes

Total number of nodes

Type:

int

nclasses

Number of job classes

Type:

int

nchains

Number of chains (routing chains)

Type:

int

nclosedjobs

Total number of jobs in closed classes

Type:

int

njobs

(1, K) Population per class (inf for open classes)

Type:

numpy.ndarray

nservers

(M, 1) Number of servers per station

Type:

numpy.ndarray

rates

(M, K) Service rates

Type:

numpy.ndarray

scv

(M, K) Squared coefficient of variation

Type:

numpy.ndarray

visits

Dict[int, ndarray] - Chain ID -> (M, K) visit ratios

Type:

Dict[int, numpy.ndarray]

inchain

Dict[int, ndarray] - Chain ID -> class indices in chain

Type:

Dict[int, numpy.ndarray]

chains

(K, 1) Chain membership per class

Type:

numpy.ndarray

refstat

(K, 1) Reference station per class

Type:

numpy.ndarray

refclass

(1, C) Reference class per chain

Type:

numpy.ndarray

sched

Dict[int, SchedStrategy] - Station ID -> scheduling strategy

Type:

Dict[int, int]

routing

(N, K) Routing strategy matrix

Type:

numpy.ndarray

rt

Routing probability matrix

Type:

numpy.ndarray | None

nodetype

List[NodeType] - Node types

Type:

List[int]

isstation

(N, 1) Boolean mask for stations

Type:

numpy.ndarray

isstateful

(N, 1) Boolean mask for stateful nodes

Type:

numpy.ndarray

nodeToStation

(N, 1) Node index -> station index mapping

Type:

numpy.ndarray

nodeToStateful

(N, 1) Node index -> stateful index mapping

Type:

numpy.ndarray

stationToNode

(M, 1) Station index -> node index mapping

Type:

numpy.ndarray

stationToStateful

(M, 1) Station index -> stateful index mapping

Type:

numpy.ndarray

statefulToNode

(S, 1) Stateful index -> node index mapping

Type:

numpy.ndarray

statefulToStation

(S, 1) Stateful index -> station index mapping

Type:

numpy.ndarray

state

Dict State per stateful node

Type:

Dict[int, numpy.ndarray]

lldscaling

(M, Nmax) Load-dependent scaling matrix

Type:

numpy.ndarray | None

cdscaling

Class-dependent scaling functions

Type:

Dict | None

cap

(M, 1) Station capacities

Type:

numpy.ndarray | None

classcap

(M, K) Per-class capacities

Type:

numpy.ndarray | None

connmatrix

(N, N) Connection matrix

Type:

numpy.ndarray | None

nodenames

List[str] - Node names

Type:

List[str]

classnames

List[str] - Class names

Type:

List[str]

__post_init__()[source]

Ensure arrays are MatrixArray (numpy arrays with .get()/.set() methods).

__repr__()[source]

String representation.

__setattr__(name, value)[source]

Override to convert numpy arrays to MatrixArray for API compatibility.

cap: numpy.ndarray | None = None
cdscaling: Dict | None = None
classcap: numpy.ndarray | None = None
classdeadline: numpy.ndarray | None = None
classprio: numpy.ndarray | None = None
connmatrix: numpy.ndarray | None = None
copy()[source]

Create a deep copy of this NetworkStruct.

csmask: numpy.ndarray | None = None
droprule: Dict | None = None
fj: numpy.ndarray | None = None
get_chain_population(chain_id)[source]

Get total population in a chain.

Parameters:

chain_id (int) – Chain index (0-based)

Returns:

Total number of jobs in the chain

Return type:

float

get_closed_class_indices()[source]

Get indices of closed classes.

get_open_class_indices()[source]

Get indices of open classes.

get_scheduling_at_station(station_id)[source]

Get scheduling strategy at a station.

Parameters:

station_id (int) – Station index (0-based)

Returns:

SchedStrategy value

Return type:

int

get_stateful_indices()[source]

Get indices of stateful nodes.

Returns:

Array of node indices that are stateful

Return type:

numpy.ndarray

get_station_indices()[source]

Get indices of station nodes.

Returns:

Array of node indices that are stations

Return type:

numpy.ndarray

get_total_population()[source]

Get total population across all closed classes.

gsync: Dict | None = None
has_class_dependence()[source]

Check if model has class-dependent scaling.

has_closed_classes()[source]

Check if model has closed (finite population) classes.

has_load_dependence()[source]

Check if model has load-dependent service rates.

has_multi_server()[source]

Check if any station has multiple servers.

has_open_classes()[source]

Check if model has open (infinite population) classes.

is_closed_chain(chain_id)[source]

Check if a chain is closed (finite population).

Parameters:

chain_id (int) – Chain index (0-based)

Returns:

True if chain is closed, False if open

Return type:

bool

is_open_chain(chain_id)[source]

Check if a chain is open (infinite population).

Parameters:

chain_id (int) – Chain index (0-based)

Returns:

True if chain is open, False if closed

Return type:

bool

is_valid()[source]

Check if structure is valid.

Returns:

True if structure passes validation, False otherwise

Return type:

bool

issignal: numpy.ndarray | None = None
isslc: numpy.ndarray | None = None
isstatedep: numpy.ndarray | None = None
lldscaling: numpy.ndarray | None = None
lst: Dict | None = None
mu: Dict | None = None
nchains: int = 0
nclasses: int = 0
nclosedjobs: int = 0
nnodes: int = 0
nodeparam: Dict | None = None
nregions: int = 0
nstateful: int = 0
nstations: int = 0
nvars: numpy.ndarray | None = None
property obj

Return self for compatibility with wrapper code that accesses .obj

phases: numpy.ndarray | None = None
phaseshift: numpy.ndarray | None = None
phasessz: numpy.ndarray | None = None
phi: Dict | None = None
pie: Dict | None = None
proc: Dict | None = None
procid: Dict | None = None
region: List | None = None
regionrule: numpy.ndarray | None = None
regionsz: numpy.ndarray | None = None
regionweight: numpy.ndarray | None = None
reward: Dict | None = None
rt: numpy.ndarray | None = None
rtnodes: numpy.ndarray | None = None
rtorig: Dict | None = None
schedparam: numpy.ndarray | None = None
signaltype: List | None = None
sync: Dict | None = None
syncreply: numpy.ndarray | None = None
validate()[source]

Validate structural consistency.

Raises:

ValueError – If structural consistency is violated

njobs: numpy.ndarray
nservers: numpy.ndarray
rates: numpy.ndarray
scv: numpy.ndarray
visits: Dict[int, numpy.ndarray]
nodevisits: Dict[int, numpy.ndarray]
inchain: Dict[int, numpy.ndarray]
chains: numpy.ndarray
refstat: numpy.ndarray
refclass: numpy.ndarray
sched: Dict[int, int]
routing: numpy.ndarray
nodetype: List[int]
isstation: numpy.ndarray
isstateful: numpy.ndarray
nodeToStation: numpy.ndarray
nodeToStateful: numpy.ndarray
stationToNode: numpy.ndarray
stationToStateful: numpy.ndarray
statefulToNode: numpy.ndarray
statefulToStation: numpy.ndarray
state: Dict[int, numpy.ndarray]
stateprior: Dict[int, numpy.ndarray]
space: Dict[int, numpy.ndarray]
nodenames: List[str]
classnames: List[str]
class NodeType(*values)[source]

Bases: IntEnum

Node types in a queueing network.

NOTE: Values must match lang/base.py NodeType enum.

static toText(node_type)[source]

Convert node type to text representation.

SOURCE = 0
SINK = 1
QUEUE = 2
DELAY = 3
JOIN = 5
CACHE = 6
ROUTER = 7
CLASSSWITCH = 8
PLACE = 9
TRANSITION = 10
LOGGER = 11
FINITE_CAPACITY_REGION = 12
class SchedStrategy(*values)[source]

Bases: IntEnum

Scheduling strategies.

LCFSPI = 3
HOL = 9
LPS = 17
SETF = 18
class RoutingStrategy(*values)[source]

Bases: IntEnum

Routing strategies.

RL = 6
CLASS_SWITCH = 8
class DropStrategy(*values)[source]

Bases: IntEnum

Drop strategies for finite capacity.

WAITQ = 0
DROP = 1
BAS = 2
sn_get_demands_chain(sn)[source]

Calculate new queueing network parameters after aggregating classes into chains.

This function computes chain-level demands, service times, visit ratios, and other parameters by aggregating class-level data based on chain membership.

Parameters:

sn (NetworkStruct) – NetworkStruct object for the queueing network model

Returns:

  • Lchain: (M, C) chain-level demand matrix

  • STchain: (M, C) chain-level service time matrix

  • Vchain: (M, C) chain-level visit ratio matrix

  • alpha: (M, K) class-to-chain weighting matrix

  • Nchain: (1, C) population per chain

  • SCVchain: (M, C) chain-level squared coefficient of variation

  • refstatchain: (C, 1) reference station per chain

Return type:

SnGetDemandsResult containing chain parameters

class SnGetDemandsResult(Lchain, STchain, Vchain, alpha, Nchain, SCVchain, refstatchain)[source]

Bases: object

Result of sn_get_demands_chain calculation.

Lchain

(M, C) Chain-level demand matrix

Type:

numpy.ndarray

STchain

(M, C) Chain-level service time matrix

Type:

numpy.ndarray

Vchain

(M, C) Chain-level visit ratio matrix

Type:

numpy.ndarray

alpha

(M, K) Class-to-chain weighting matrix

Type:

numpy.ndarray

Nchain

(1, C) Population per chain

Type:

numpy.ndarray

SCVchain

(M, C) Chain-level squared coefficient of variation

Type:

numpy.ndarray

refstatchain

(C, 1) Reference station per chain

Type:

numpy.ndarray

Lchain: numpy.ndarray
STchain: numpy.ndarray
Vchain: numpy.ndarray
alpha: numpy.ndarray
Nchain: numpy.ndarray
SCVchain: numpy.ndarray
refstatchain: numpy.ndarray
sn_deaggregate_chain_results(sn, Lchain, ST, STchain, Vchain, alpha, Qchain, Uchain, Rchain, Tchain, Cchain, Xchain)[source]

Calculate class-based performance metrics from chain-level performance measures.

This function disaggregates chain-level performance metrics (queue lengths, utilizations, response times, throughputs) to class-level metrics using the aggregation factors (alpha).

Parameters:
  • sn (NetworkStruct) – NetworkStruct object for the queueing network model

  • Lchain (numpy.ndarray) – (M, C) Service demands per chain

  • ST (numpy.ndarray | None) – (M, K) Mean service times per class (optional, computed from rates if None)

  • STchain (numpy.ndarray) – (M, C) Mean service times per chain

  • Vchain (numpy.ndarray) – (M, C) Mean visits per chain

  • alpha (numpy.ndarray) – (M, K) Class aggregation coefficients

  • Qchain (numpy.ndarray | None) – (M, C) Mean queue-lengths per chain (optional)

  • Uchain (numpy.ndarray | None) – (M, C) Mean utilization per chain (optional)

  • Rchain (numpy.ndarray) – (M, C) Mean response time per chain

  • Tchain (numpy.ndarray) – (M, C) Mean throughput per chain

  • Cchain (numpy.ndarray | None) – (1, C) Mean system response time per chain (optional, not yet supported)

  • Xchain (numpy.ndarray) – (1, C) Mean system throughput per chain

Returns:

  • Q: (M, K) queue lengths

  • U: (M, K) utilizations

  • R: (M, K) response times

  • T: (M, K) throughputs

  • C: (1, K) system response times

  • X: (1, K) system throughputs

Return type:

SnDeaggregateResult containing class-level performance metrics

Raises:

RuntimeError – If Cchain is provided (not yet supported)

class SnDeaggregateResult(Q, U, R, T, C, X)[source]

Bases: object

Result of sn_deaggregate_chain_results calculation.

Q

(M, K) Class-level queue lengths

Type:

numpy.ndarray

U

(M, K) Class-level utilizations

Type:

numpy.ndarray

R

(M, K) Class-level response times

Type:

numpy.ndarray

T

(M, K) Class-level throughputs

Type:

numpy.ndarray

C

(1, K) Class-level system response times

Type:

numpy.ndarray

X

(1, K) Class-level system throughputs

Type:

numpy.ndarray

Q: numpy.ndarray
U: numpy.ndarray
R: numpy.ndarray
T: numpy.ndarray
C: numpy.ndarray
X: numpy.ndarray
class ProductFormParams(lam, D, N, Z, mu, S, V)[source]

Bases: NamedTuple

Result of sn_get_product_form_params calculation.

Create new instance of ProductFormParams(lam, D, N, Z, mu, S, V)

D: numpy.ndarray

Alias for field number 1

N: numpy.ndarray

Alias for field number 2

S: numpy.ndarray

Alias for field number 5

V: numpy.ndarray

Alias for field number 6

Z: numpy.ndarray

Alias for field number 3

lam: numpy.ndarray

Alias for field number 0

mu: numpy.ndarray

Alias for field number 4

sn_get_product_form_params(sn)[source]

Extract standard product-form parameters from the network structure.

This function extracts class-level parameters from a network structure for use in product-form queueing network analysis.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

  • lam: Arrival rates for open classes

  • D: Service demands at queueing stations

  • N: Population vector

  • Z: Think times (service demands at delay stations)

  • mu: Load-dependent service capacity scaling factors

  • S: Number of servers at queueing stations

  • V: Visit ratios

Return type:

ProductFormParams containing

References

MATLAB: matlab/src/api/sn/sn_get_product_form_params.m

sn_get_residt_from_respt(sn, RN, WH=None)[source]

Compute residence times from response times.

This function converts response times to residence times by accounting for visit ratios at each station.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object

  • RN (numpy.ndarray) – Average response times (M, K)

  • WH (Dict | None) – Residence time handles (optional)

Returns:

Average residence times (M, K)

Return type:

WN

References

MATLAB: matlab/src/api/sn/sn_get_residt_from_respt.m

sn_get_state_aggr(sn)[source]

Get aggregated state representation.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

Dictionary mapping stateful node index to aggregated state

Return type:

Dict[int, numpy.ndarray]

References

MATLAB: matlab/src/api/sn/sn_get_state_aggr.m

sn_set_arrival(sn, station_idx, class_idx, rate)[source]

Set arrival rate for a class at a station.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • station_idx (int) – Station index (0-based)

  • class_idx (int) – Class index (0-based)

  • rate (float) – Arrival rate

References

MATLAB: matlab/src/api/sn/sn_set_arrival.m

sn_set_service(sn, station_idx, class_idx, rate, scv=1.0)[source]

Set service rate for a class at a station.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • station_idx (int) – Station index (0-based)

  • class_idx (int) – Class index (0-based)

  • rate (float) – Service rate

  • scv (float) – Squared coefficient of variation (default 1.0 for exponential)

References

MATLAB: matlab/src/api/sn/sn_set_service.m

sn_set_servers(sn, station_idx, nservers)[source]

Set number of servers at a station.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • station_idx (int) – Station index (0-based)

  • nservers (int) – Number of servers

References

MATLAB: matlab/src/api/sn/sn_set_servers.m

sn_set_population(sn, class_idx, njobs)[source]

Set population for a class.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • class_idx (int) – Class index (0-based)

  • njobs (float) – Number of jobs (inf for open class)

References

MATLAB: matlab/src/api/sn/sn_set_population.m

sn_set_priority(sn, class_idx, priority)[source]

Set priority for a class.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • class_idx (int) – Class index (0-based)

  • priority (int) – Priority level (higher = more priority)

References

MATLAB: matlab/src/api/sn/sn_set_priority.m

sn_set_routing(sn, source_node, dest_node, source_class, dest_class, prob)[source]

Set routing probability between nodes and classes.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (modified in place)

  • source_node (int) – Source node index (0-based)

  • dest_node (int) – Destination node index (0-based)

  • source_class (int) – Source class index (0-based)

  • dest_class (int) – Destination class index (0-based)

  • prob (float) – Routing probability

References

MATLAB: matlab/src/api/sn/sn_set_routing.m

sn_refresh_visits(sn)[source]

Refresh visit ratios from routing matrix.

This function solves traffic equations to compute visit ratios at each station from the routing probability matrix.

Parameters:

sn (NetworkStruct) – NetworkStruct object (modified in place)

References

MATLAB: matlab/src/api/sn/sn_refresh_visits.m

sn_set_fork_fanout(sn, fork_node_idx, fan_out)[source]

Set fork fanout (tasksPerLink) for a Fork node.

Updates the fanOut field in nodeparam for a Fork node.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object

  • fork_node_idx (int) – Node index of the Fork node (0-based)

  • fan_out (int) – Number of tasks per output link (>= 1)

Returns:

Modified NetworkStruct

Raises:

ValueError – If the specified node is not a Fork node

Return type:

NetworkStruct

References

MATLAB: matlab/src/api/sn/sn_set_fork_fanout.m

sn_set_service_batch(sn, rates, scvs=None, auto_refresh=False)[source]

Set service rates for multiple station-class pairs.

Batch update of service rates. NaN values are skipped (not updated). More efficient than calling sn_set_service multiple times.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object

  • rates (numpy.ndarray) – Matrix of new rates (nstations x nclasses), NaN = skip

  • scvs (numpy.ndarray | None) – Matrix of new SCVs (optional)

  • auto_refresh (bool) – If True, refresh process fields (default False)

Returns:

Modified NetworkStruct

Return type:

NetworkStruct

References

MATLAB: matlab/src/api/sn/sn_set_service_batch.m

sn_nonmarkov_toph(sn, options=None)[source]

Convert non-Markovian distributions to Phase-Type using approximation.

This function scans all service and arrival processes in the network structure and converts non-Markovian distributions to Markovian Arrival Processes (MAPs) using the specified approximation method.

Supported non-Markovian distributions: - GAMMA: Gamma distribution - WEIBULL: Weibull distribution - LOGNORMAL: Lognormal distribution - PARETO: Pareto distribution - UNIFORM: Uniform distribution - DET: Deterministic (converted to Erlang)

Parameters:
  • sn (NetworkStruct) – NetworkStruct object (from getStruct())

  • options (Dict[str, Any] | None) – Solver options dict with fields: - config.nonmkv: Method for conversion (‘none’, ‘bernstein’) - config.nonmkvorder: Number of phases for approximation (default 20) - config.preserveDet: Keep deterministic distributions (for MAP/D/c)

Returns:

Modified NetworkStruct with converted processes

Return type:

NetworkStruct

References

MATLAB: matlab/src/api/sn/sn_nonmarkov_toph.m

class ChainParams(lambda_vec, D, N, Z, mu, S, V)[source]

Bases: object

Chain-aggregated product-form parameters.

lambda_vec: numpy.ndarray
D: numpy.ndarray
N: numpy.ndarray
Z: numpy.ndarray
mu: numpy.ndarray
S: numpy.ndarray
V: numpy.ndarray
sn_get_arvr_from_tput(sn, TN, TH=None)[source]

Compute average arrival rates at stations from throughputs.

Calculates the average arrival rate at each station in steady-state from the station throughputs and routing matrix.

Parameters:
Returns:

Average arrival rates at stations (M x R)

Return type:

AN

References

Original MATLAB: matlab/src/api/sn/sn_get_arvr_from_tput.m

sn_get_node_arvr_from_tput(sn, TN, TH=None, AN=None)[source]

Compute node arrival rates from station throughputs.

This function handles: - Station nodes: Uses station arrival rates directly - Cache nodes: Only requesting classes arrive (not hit/miss classes) - Non-station nodes (ClassSwitch, Sink): Uses nodevisits-based computation

Parameters:
Returns:

Node arrival rates (I x R)

Return type:

ANn

References

Original MATLAB: matlab/src/api/sn/sn_get_node_arvr_from_tput.m

sn_get_node_tput_from_tput(sn, TN, TH=None, ANn=None)[source]

Compute node throughputs from station throughputs.

This function handles: - Station nodes: Uses station throughputs directly - Cache nodes: Uses actual hit/miss probabilities if available - Non-station nodes: Uses routing matrix (rtnodes) for computation

Parameters:
Returns:

Node throughputs (I x R)

Return type:

TNn

References

Original MATLAB: matlab/src/api/sn/sn_get_node_tput_from_tput.m

sn_get_product_form_chain_params(sn)[source]

Extract product-form parameters aggregated by chain.

Extracts parameters from a network structure and aggregates them by chain for use in product-form analysis methods.

Parameters:

sn (NetworkStruct) – Network structure

Returns:

ChainParams with lambda_vec, D, N, Z, mu, S, V

Return type:

ChainParams

References

Original MATLAB: matlab/src/api/sn/sn_get_product_form_chain_params.m

sn_set_routing_prob(sn, from_stateful, from_class, to_stateful, to_class, prob, auto_refresh=False)[source]

Set a routing probability between two stateful node-class pairs.

Updates a single entry in the rt matrix.

Parameters:
  • sn (NetworkStruct) – Network structure

  • from_stateful (int) – Source stateful node index (0-based)

  • from_class (int) – Source class index (0-based)

  • to_stateful (int) – Destination stateful node index (0-based)

  • to_class (int) – Destination class index (0-based)

  • prob (float) – Routing probability [0, 1]

  • auto_refresh (bool) – If True, refresh visit ratios (default False)

Returns:

Modified network structure

Return type:

NetworkStruct

References

Original MATLAB: matlab/src/api/sn/sn_set_routing_prob.m

sn_is_closed_model(sn)[source]

Check if the network model is closed (all finite populations).

A closed model has finite jobs and no infinite (open) job classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if the network is a closed model

Return type:

bool

sn_is_open_model(sn)[source]

Check if the network model is open (all infinite populations).

An open model has only infinite (open) job classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if the network is an open model

Return type:

bool

sn_is_mixed_model(sn)[source]

Check if the network model is mixed (both open and closed classes).

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if the network has both open and closed classes

Return type:

bool

sn_is_population_model(sn)[source]

Check if the network model has populations defined.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if population is defined

Return type:

bool

sn_has_closed_classes(sn)[source]

Check if the network has closed (finite population) classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one closed class

Return type:

bool

sn_has_open_classes(sn)[source]

Check if the network has open (infinite population) classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one open class

Return type:

bool

sn_has_mixed_classes(sn)[source]

Check if the network has both open and closed classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has both open and closed classes

Return type:

bool

sn_has_single_class(sn)[source]

Check if the network has exactly one class.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has exactly one class

Return type:

bool

sn_has_multi_class(sn)[source]

Check if the network has multiple classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has more than one class

Return type:

bool

sn_has_multiple_closed_classes(sn)[source]

Check if the network has multiple closed classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has more than one closed class

Return type:

bool

sn_has_single_chain(sn)[source]

Check if the network has exactly one chain.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has exactly one chain

Return type:

bool

sn_has_multi_chain(sn)[source]

Check if the network has multiple chains.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has more than one chain

Return type:

bool

sn_has_fcfs(sn)[source]

Check if the network has any FCFS (First-Come First-Served) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one FCFS station

Return type:

bool

sn_has_ps(sn)[source]

Check if the network has any PS (Processor Sharing) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one PS station

Return type:

bool

sn_has_inf(sn)[source]

Check if the network has any INF (Infinite Server/Delay) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one INF station

Return type:

bool

sn_has_lcfs(sn)[source]

Check if the network has any LCFS (Last-Come First-Served) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LCFS station

Return type:

bool

sn_has_lcfspr(sn)[source]

Check if the network has any LCFS-PR (LCFS Preemptive Resume) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LCFS-PR station

Return type:

bool

sn_has_lcfs_pi(sn)[source]

Check if the network has any LCFS-PI (LCFS Preemptive Identical) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LCFS-PI station

Return type:

bool

sn_has_siro(sn)[source]

Check if the network has any SIRO (Service In Random Order) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one SIRO station

Return type:

bool

sn_has_dps(sn)[source]

Check if the network has any DPS (Discriminatory Processor Sharing) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one DPS station

Return type:

bool

sn_has_dps_prio(sn)[source]

Check if the network has any DPS with priority stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one DPS-PRIO station

Return type:

bool

sn_has_gps(sn)[source]

Check if the network has any GPS (Generalized Processor Sharing) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one GPS station

Return type:

bool

sn_has_gps_prio(sn)[source]

Check if the network has any GPS with priority stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one GPS-PRIO station

Return type:

bool

sn_has_ps_prio(sn)[source]

Check if the network has any PS with priority stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one PS-PRIO station

Return type:

bool

sn_has_hol(sn)[source]

Check if the network has any HOL (Head of Line) priority stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one HOL station

Return type:

bool

sn_has_lps(sn)[source]

Check if the network has any LPS (Least Progress Scheduling) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LPS station

Return type:

bool

sn_has_setf(sn)[source]

Check if the network has any SETF (Shortest Elapsed Time First) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one SETF station

Return type:

bool

sn_has_sept(sn)[source]

Check if the network has any SEPT (Shortest Expected Processing Time) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one SEPT station

Return type:

bool

sn_has_lept(sn)[source]

Check if the network has any LEPT (Longest Expected Processing Time) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LEPT station

Return type:

bool

sn_has_sjf(sn)[source]

Check if the network has any SJF (Shortest Job First) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one SJF station

Return type:

bool

sn_has_ljf(sn)[source]

Check if the network has any LJF (Longest Job First) stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one LJF station

Return type:

bool

sn_has_polling(sn)[source]

Check if the network has any polling stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has at least one polling station

Return type:

bool

sn_has_homogeneous_scheduling(sn, strategy)[source]

Check if the network uses an identical scheduling strategy at every station.

Parameters:
  • sn (NetworkStruct) – NetworkStruct object

  • strategy (int) – SchedStrategy value to check for

Returns:

True if all stations use the specified strategy

Return type:

bool

sn_has_multi_class_fcfs(sn)[source]

Check if the network has a multiclass FCFS station.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has multiclass and at least one FCFS station

Return type:

bool

sn_has_multi_class_heter_fcfs(sn)[source]

Check if network has multiclass heterogeneous FCFS stations.

A heterogeneous FCFS station has different service rates for different classes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has FCFS stations with heterogeneous class rates

Return type:

bool

sn_has_multi_class_heter_exp_fcfs(sn)[source]

Check if network has multiclass heterogeneous exponential FCFS stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has FCFS stations with heterogeneous exponential service

Return type:

bool

sn_has_multi_server(sn)[source]

Check if the network has any multi-server stations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if any station has more than one server

Return type:

bool

sn_has_load_dependence(sn)[source]

Check if the network has load-dependent service.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has load-dependent scaling

Return type:

bool

sn_has_joint_dependence(sn)[source]

Check if the network has joint-dependent service rates.

This includes both LJD (Limited Joint Dependence) and LJCD (Limited Joint Class Dependence) scaling.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has joint-dependent scaling

Return type:

bool

sn_has_fork_join(sn)[source]

Check if the network uses fork and/or join nodes.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has fork-join topology

Return type:

bool

sn_has_priorities(sn)[source]

Check if the network uses class priorities.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if the network has priority-based scheduling (non-uniform priorities)

Return type:

bool

sn_has_class_switching(sn)[source]

Check if the network has class switching.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has class switching

Return type:

bool

sn_has_fractional_populations(sn)[source]

Check if the network has fractional (non-integer) populations.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if any class has fractional population

Return type:

bool

sn_has_sd_routing(sn)[source]

Check if the network has state-dependent routing strategies.

State-dependent routing strategies violate the product-form assumption. These include Round-Robin, Weighted Round-Robin, Join Shortest Queue, Power of K Choices, and Reinforcement Learning.

Product-form requires state-independent (Markovian) routing. PROB and RAND are product-form compatible.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has state-dependent routing

Return type:

bool

sn_has_product_form(sn)[source]

Check if the network has a known product-form solution.

A network has product form if: - All stations use INF, PS, FCFS, LCFS-PR, or EXT scheduling - No multiclass heterogeneous FCFS - No priorities - No fork-join

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network has product-form solution

Return type:

bool

sn_has_product_form_not_het_fcfs(sn)[source]

Check if network has product form except for heterogeneous FCFS.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network would have product form without heterogeneous FCFS

Return type:

bool

sn_has_product_form_except_multi_class_heter_exp_fcfs(sn)[source]

Check if network has product form except for multiclass heterogeneous exponential FCFS.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if network would have product form without multiclass heter exp FCFS

Return type:

bool

sn_is_state_valid(sn)[source]

Check if the network state is valid.

Parameters:

sn (NetworkStruct) – NetworkStruct object

Returns:

True if state is valid

Return type:

bool

sn_print(sn, file=None)[source]

Print comprehensive information about a NetworkStruct object.

This function displays all fields, matrices, lists, and maps in a formatted manner useful for debugging and inspection of network structures.

Parameters:
  • sn (NetworkStruct) – Network structure to inspect

  • file – Output file (default: sys.stdout)

References

MATLAB: matlab/src/api/sn/sn_print.m

sn_print_routing_matrix(sn, onlyclass=None, file=None)[source]

Print the routing matrix of the network.

This function displays the routing probabilities between nodes and classes in a human-readable format.

Parameters:
  • sn (NetworkStruct) – Network structure

  • onlyclass (Any | None) – Optional filter for a specific class (object with ‘name’ attribute)

  • file – Output file (default: sys.stdout)

References

MATLAB: matlab/src/api/sn/sn_print_routing_matrix.m

sn_refresh_process_fields(sn, station_idx, class_idx)[source]

Refresh process fields based on rate and SCV values.

Updates mu, phi, proc, pie, phases based on current rate and SCV values. - SCV = 1.0: Exponential (1 phase) - SCV < 1.0: Erlang approximation - SCV > 1.0: Hyperexponential(2) approximation

Parameters:
  • sn (NetworkStruct) – Network structure (modified in place)

  • station_idx (int) – Station index (0-based)

  • class_idx (int) – Class index (0-based)

Returns:

Modified network structure

Return type:

NetworkStruct

References

MATLAB: matlab/src/api/sn/sn_refresh_process_fields.m

sn_rtnodes_to_rtorig(sn)[source]

Convert node routing matrix to the original routing matrix format.

This function converts the node-level routing matrix to the original routing matrix format, excluding class-switching nodes.

Parameters:

sn (NetworkStruct) – Network structure

Returns:

rtorigcell: Dictionary representation {(r,s): ndarray} rtorig: Sparse/dense matrix representation

Return type:

Tuple of (rtorigcell, rtorig) where

References

MATLAB: matlab/src/api/sn/sn_rtnodes_to_rtorig.m

Non-Product-Form Networks (line_solver.api.npfqn)

Non-Product-Form Queueing Network (NPFQN) algorithms.

Native Python implementations for approximating performance of non-product-form queueing networks.

Key algorithms:

npfqn_nonexp_approx: Non-exponential distribution approximation npfqn_traffic_merge: Merge multiple MMAP traffic flows npfqn_traffic_merge_cs: Merge traffic flows with class switching npfqn_traffic_split_cs: Split traffic flows with class switching

npfqn_nonexp_approx(method, sn, ST, V, SCV, Tin, Uin, gamma, nservers)[source]

Approximates non-product-form queueing networks using the specified method.

This function adjusts service times and other parameters to account for non-exponential service time distributions in product-form analysis.

Parameters:
  • method (str) – Approximation method (“default”, “none”, “hmva”, “interp”)

  • sn (NetworkStruct) – Network structure

  • ST (ndarray) – Service time matrix (M x K)

  • V (ndarray | None) – Visit ratios matrix (M x K), optional

  • SCV (ndarray) – Squared coefficient of variation matrix (M x K)

  • Tin (ndarray) – Initial throughput matrix (M x K)

  • Uin (ndarray) – Initial utilization matrix (M x K)

  • gamma (ndarray) – Gamma correction matrix (M x 1)

  • nservers (ndarray) – Number of servers matrix (M x 1)

Returns:

NpfqnNonexpApproxResult with updated matrices

Raises:

ValueError – If unknown approximation method is specified

Return type:

NpfqnNonexpApproxResult

class NpfqnNonexpApproxResult(ST, gamma, nservers, rho, scva, scvs, eta)[source]

Bases: object

Result of non-exponential approximation.

ST: ndarray
gamma: ndarray
nservers: ndarray
rho: ndarray
scva: ndarray
scvs: ndarray
eta: ndarray
npfqn_traffic_merge(MMAPa, config_merge='default', config_compress=None)[source]

Merge multiple MMAP traffic flows.

Combines multiple MMAPs using specified aggregation strategies. Supports various merge configurations for different network topologies.

Parameters:
  • MMAPa (Dict[int, List[ndarray] | None]) – Dictionary of MMAP traffic flows to be merged. Keys are integer indices, values are MMAP lists [D0, D1, …].

  • config_merge (str) – Merge configuration. Options: - “default”, “super”: Use MMAP superposition - “mixture”: Apply mixture fitting after superposition - “interpos”: Interposition method (falls back to super)

  • config_compress (str | None) – Compression configuration. Options: - None, “none”: No compression - “default”: Apply default compression

Returns:

Merged and normalized MMAP, or None if input is empty.

Raises:

RuntimeError – If unsupported merge configuration is provided.

Return type:

List[ndarray] | None

Example

>>> mmap1 = [np.array([[-1.0]]), np.array([[1.0]])]
>>> mmap2 = [np.array([[-2.0]]), np.array([[2.0]])]
>>> result = npfqn_traffic_merge({0: mmap1, 1: mmap2})
npfqn_traffic_merge_cs(MMAPs, prob, config='default')[source]

Merge MMAP traffic flows with class switching.

Combines multiple MMAPs while applying class switching transformations based on the probability matrix.

Parameters:
  • MMAPs (Dict[int, List[ndarray]]) – Dictionary of MMAP traffic flows indexed by source.

  • prob (ndarray) –

    Class switching probability matrix ((n*R) x R) where: - n is the number of sources - R is the number of classes - prob[(i-1)*R + r, s] = probability that class r from source i

    becomes class s in the merged stream

  • config (str) – Merge configuration (“default” or “super”).

Returns:

Merged MMAP with class switching applied, or None if empty.

Return type:

List[ndarray] | None

Algorithm:
  1. Apply mmap_mark to each source MMAP to encode class switching

  2. Superpose all marked MMAPs

  3. Return result

Example

>>> mmap1 = [np.array([[-1.0]]), np.array([[0.5]]), np.array([[0.5]])]
>>> mmap2 = [np.array([[-2.0]]), np.array([[1.0]]), np.array([[1.0]])]
>>> prob = np.array([[0.8, 0.2], [0.3, 0.7], [0.6, 0.4], [0.5, 0.5]])
>>> result = npfqn_traffic_merge_cs({0: mmap1, 1: mmap2}, prob)
npfqn_traffic_split_cs(MMAP_input, P)[source]

Split MMAP traffic flows with class switching.

Decomposes a single MMAP into multiple MMAPs based on routing probabilities and class switching matrix.

Parameters:
  • MMAP_input (List[ndarray]) – Input MMAP as list [D0, D1, D2, …].

  • P (ndarray) –

    Class switching probability matrix (R x J) where: - R is the number of arrival classes - J = M * R where M is the number of destinations - P[r, (jst-1)*R + s] = probability that class r arrival

    becomes class s at destination jst

Returns:

Dictionary mapping destination index to split MMAP. Keys are 0-indexed destination indices.

Return type:

Dict[int, List[ndarray] | None]

Algorithm:
  1. Parse dimensions from P matrix

  2. For each destination, create MMAP with weighted marking matrices

  3. Normalize each result

Example

>>> mmap = [np.array([[-3.0]]), np.array([[1.0]]), np.array([[2.0]])]
>>> P = np.array([[0.8, 0.2, 0.5, 0.5], [0.3, 0.7, 0.6, 0.4]])
>>> result = npfqn_traffic_split_cs(mmap, P)

Polling Systems (line_solver.api.polling)

Polling System Analysis Algorithms.

Native Python implementations for analyzing polling/vacation queue systems with various disciplines.

Key algorithms:

polling_qsys_exhaustive: Exhaustive polling discipline polling_qsys_gated: Gated polling discipline polling_qsys_1limited: 1-Limited polling discipline

polling_qsys_exhaustive(arvMAPs, svcMAPs, switchMAPs)[source]

Compute exact mean waiting times for exhaustive polling system.

In exhaustive polling, the server continues to serve a queue until it becomes empty before moving to the next queue.

Based on Takagi, ACM Computing Surveys, Vol. 20, No. 1, 1988, eq (15).

Parameters:
Returns:

Array of mean waiting times for each queue.

Return type:

ndarray

polling_qsys_gated(arvMAPs, svcMAPs, switchMAPs)[source]

Compute exact mean waiting times for gated polling system.

In gated polling, the server serves all customers present at the beginning of a visit period.

Based on Takagi, ACM Computing Surveys, Vol. 20, No. 1, 1988, eq (20).

Parameters:
Returns:

Array of mean waiting times for each queue.

Return type:

ndarray

polling_qsys_1limited(arvMAPs, svcMAPs, switchMAPs)[source]

Compute exact mean waiting times for 1-limited polling system.

In 1-limited polling, the server serves at most one customer from each queue before moving to the next queue.

Based on Takagi, ACM Computing Surveys, Vol. 20, No. 1, 1988, eq (20).

Parameters:
Returns:

Array of mean waiting times for each queue.

Return type:

ndarray

Loss Networks (line_solver.api.lossn)

Loss Network Analysis Algorithms.

Native Python implementations for analyzing loss networks using Erlang formulas and related methods.

Key algorithms:

lossn_erlangfp: Erlang fixed-point algorithm for loss networks erlang_b: Erlang B blocking probability erlang_c: Erlang C delay probability

lossn_erlangfp(nu, A, c, tol=1e-8, max_iter=1000)[source]

Erlang fixed point approximation for loss networks.

Calls (jobs) on route (class) r arrive according to Poisson rate nu_r. Call service times on route r have unit mean.

The link capacity requirements are:

sum_r A[j,r] * n[j,r] < c[j]

for all links j, where n[j,r] counts calls on route r on link j.

Parameters:
  • nu (ndarray) – Arrival rates vector (R,) for each route.

  • A (ndarray) – Capacity requirement matrix (J, R) - A[j,r] is capacity required on link j by route r.

  • c (ndarray) – Capacity vector (J,) - c[j] is capacity of link j.

  • tol (float) – Convergence tolerance.

  • max_iter (int) – Maximum iterations.

Returns:

  • qlen: Mean queue-length for each route (R,)

  • loss: Loss probability for each route (R,)

  • eblock: Blocking probability for each link (J,)

  • niter: Number of iterations

Return type:

Tuple of (qlen, loss, eblock, niter) where

Example

>>> nu = np.array([0.3, 0.1])
>>> A = np.array([[1, 1], [1, 4]])  # 2 links, 2 routes
>>> c = np.array([1, 3])
>>> qlen, loss, eblock, niter = lossn_erlangfp(nu, A, c)
erlang_b(offered_load, servers)[source]

Compute Erlang B blocking probability.

The Erlang B formula gives the probability that an arriving call is blocked in an M/M/c/c loss system.

Parameters:
  • offered_load (float) – Traffic intensity (arrival rate * service time).

  • servers (int) – Number of servers.

Returns:

Blocking probability.

Return type:

float

Example

>>> erlang_b(10.0, 12)  # Offered load 10 Erlang, 12 channels
0.1054...
erlang_c(offered_load, servers)[source]

Compute Erlang C delay probability.

The Erlang C formula gives the probability that an arriving call must wait in an M/M/c queue.

Parameters:
  • offered_load (float) – Traffic intensity (arrival rate * service time).

  • servers (int) – Number of servers.

Returns:

Delay probability (probability of waiting).

Return type:

float

Example

>>> erlang_c(10.0, 12)  # Offered load 10 Erlang, 12 agents

Layered Stochastic Networks (line_solver.api.lsn)

Layered Stochastic Network (LSN) utilities.

Native Python implementations for layered queueing network analysis.

Key functions:

lsn_max_multiplicity: Compute maximum multiplicity for tasks in a layered network.

Key classes:

LayeredNetworkStruct: Structure representing a layered network. LayeredNetworkElement: Enumeration of layered network element types.

class LayeredNetworkElement(*values)[source]

Bases: IntEnum

Types of elements in a layered network.

TASK = 1
ENTRY = 2
ACTIVITY = 3
PROCESSOR = 4
HOST = 5
class LayeredNetworkStruct(dag, mult, type, isref)[source]

Bases: object

Structure representing a layered network for LSN analysis.

dag

Directed acyclic graph adjacency matrix (n x n). dag[i,j] > 0 indicates an edge from node i to node j.

Type:

numpy.ndarray

mult

Multiplicity (max concurrent instances) for each node (n,).

Type:

numpy.ndarray

type

Node type for each node (n,), using LayeredNetworkElement values.

Type:

numpy.ndarray

isref

Reference task flags (n,). Non-zero indicates a reference task.

Type:

numpy.ndarray

dag: ndarray
mult: ndarray
type: ndarray
isref: ndarray
kahn_topological_sort(adjacency)[source]

Perform Kahn’s algorithm for topological sorting.

Parameters:

adjacency (ndarray) – Adjacency matrix where adjacency[i,j] > 0 means edge i -> j.

Returns:

List of node indices in topological order.

Raises:

ValueError – If the graph contains a cycle.

Return type:

List[int]

lsn_max_multiplicity(lsn)[source]

Compute the maximum multiplicity for each task in a layered network.

This function uses flow analysis based on Kahn’s topological sorting algorithm to determine the maximum sustainable throughput for each task, considering both the incoming flow and the multiplicity constraints.

Parameters:

lsn (LayeredNetworkStruct) – The layered network structure containing task dependencies and constraints.

Returns:

Matrix of maximum multiplicities for each task in the network (n x 1).

Return type:

ndarray

Algorithm:
  1. Build binary adjacency graph from DAG

  2. Apply Kahn’s topological sort to determine processing order

  3. Initialize inflow from reference tasks

  4. For each node in topological order: - outflow = min(inflow, multiplicity constraint) - Propagate outflow to downstream nodes

  5. Handle unreachable tasks (infinite multiplicity)

Example

>>> lsn = LayeredNetworkStruct(
...     dag=np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]),
...     mult=np.array([2, 3, 5]),
...     type=np.array([1, 1, 1]),
...     isref=np.array([1, 0, 0])
... )
>>> max_mult = lsn_max_multiplicity(lsn)

Trace Analysis (line_solver.api.trace)

Trace Analysis Functions.

Native Python implementations for statistical analysis of empirical trace data including means, variances, correlations, and index of dispersion.

Key functions:

trace_mean: Mean of trace data trace_var: Variance of trace data trace_scv: Squared coefficient of variation trace_acf: Autocorrelation function trace_summary: Comprehensive summary statistics

trace_mean(trace)[source]

Compute the arithmetic mean of trace data.

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

Mean value of the trace.

Return type:

float

Example

>>> trace_mean([1.0, 2.0, 3.0, 4.0, 5.0])
3.0
trace_var(trace)[source]

Compute the variance of trace data.

Uses population variance (ddof=0) for consistency with Kotlin.

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

Variance of the trace.

Return type:

float

Example

>>> trace_var([1.0, 2.0, 3.0, 4.0, 5.0])
2.0
trace_scv(trace)[source]

Compute the squared coefficient of variation (SCV).

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

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

Squared coefficient of variation.

Return type:

float

Example

>>> trace_scv([1.0, 2.0, 3.0])  # Var=0.667, Mean=2, SCV=0.167
trace_acf(trace, lags=None)[source]

Compute the autocorrelation function at specified lags.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • lags (ndarray | list) – Array of lag values (default: [1]).

Returns:

Array of autocorrelation values at each lag.

Return type:

ndarray

Example

>>> trace = np.random.randn(100)
>>> acf = trace_acf(trace, [1, 2, 3])
trace_gamma(trace, limit=1000)[source]

Estimate the autocorrelation decay rate of a trace.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • limit (int) – Maximum lag considered.

Returns:

Array containing [GAMMA, RHO0, RESIDUALS].

Return type:

ndarray

Example

>>> gamma, rho0, residuals = trace_gamma(trace_data)
trace_iat2counts(trace, scale)[source]

Compute the counting process from inter-arrival times.

Parameters:
  • trace (ndarray | list) – Array of inter-arrival times.

  • scale (float) – Time scale for counting.

Returns:

Array of counts after scale units of time from each arrival.

Return type:

ndarray

Example

>>> iat = [0.5, 0.3, 0.8, 0.2, 0.4]
>>> counts = trace_iat2counts(iat, 1.0)
trace_idi(trace, kset, option=None, n=1)[source]

Compute the Index of Dispersion for Intervals.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • kset (ndarray | list) – Set of k values to compute IDI for.

  • option (str) – Aggregation option (None, ‘aggregate’, ‘aggregate-mix’).

  • n (int) – Aggregation parameter.

Returns:

Tuple of (IDI values, support values).

Return type:

Tuple[ndarray, ndarray]

Example

>>> idi, support = trace_idi(trace_data, [10, 20, 50])
trace_idc(trace)[source]

Compute the Index of Dispersion for Counts.

Asymptotically equal to IDI.

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

IDC value.

Return type:

float

Example

>>> idc = trace_idc(inter_arrival_times)
trace_pmf(X)[source]

Compute the probability mass function of discrete data.

Parameters:

X (ndarray | list) – Array of discrete values.

Returns:

Tuple of (PMF values, unique values).

Return type:

Tuple[ndarray, ndarray]

Example

>>> pmf, values = trace_pmf([1, 2, 2, 3, 3, 3])
trace_shuffle(trace)[source]

Shuffle trace data randomly.

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

Shuffled trace array.

Return type:

ndarray

Example

>>> shuffled = trace_shuffle([1, 2, 3, 4, 5])
trace_joint(trace, lag, order)[source]

Compute joint moments E[X^{k_1}_{i} * X^{k_2}_{i+j} * …].

Parameters:
Returns:

Joint moment value.

Return type:

float

Example

>>> jm = trace_joint(trace, [0, 1], [1, 1])  # E[X_i * X_{i+1}]
trace_iat2bins(trace, scale)[source]

Compute counts in bins with specified timescale.

Parameters:
  • trace (ndarray | list) – Array of inter-arrival times.

  • scale (float) – Bin timescale.

Returns:

Tuple of (counts per bin, bin membership for each element).

Return type:

Tuple[ndarray, ndarray]

Example

>>> counts, bins = trace_iat2bins(iat_data, 1.0)
trace_summary(trace)[source]

Compute comprehensive summary statistics for a trace.

Parameters:

trace (ndarray | list) – Array of trace values.

Returns:

Array containing [MEAN, SCV, MAD, SKEW, KURT, Q25, Q50, Q75, P95, MIN, MAX, IQR, ACF1, ACF2, ACF3, ACF4, IDC_SCV_RATIO].

Return type:

ndarray

Example

>>> summary = trace_summary(trace_data)
>>> print(f"Mean: {summary[0]}, SCV: {summary[1]}")
trace_bicov(trace, grid)[source]

Compute bicovariance of a trace.

Bicovariance measures third-order correlation structure at multiple lag combinations.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • grid (ndarray | list) – Array of lags to form the grid (e.g., [1, 2, 3, 4, 5]).

Returns:

  • bicov: Array of bicovariance values

  • bicov_lags: 2D array of lag combinations (each row is [1, i, j])

Return type:

Tuple of (bicov, bicov_lags) where

Example

>>> trace = np.random.randn(1000)
>>> bicov, lags = trace_bicov(trace, [1, 2, 3, 4, 5])
mtrace_mean(trace, ntypes, types)[source]

Compute the mean of a trace, divided by types.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • ntypes (int) – Number of different types.

  • types (ndarray | list) – Array indicating the type of each element.

Returns:

Array containing the mean values for each type.

Return type:

ndarray

Example

>>> trace = [1.0, 2.0, 3.0, 4.0]
>>> types = [0, 1, 0, 1]
>>> means = mtrace_mean(trace, 2, types)
mtrace_var(trace, ntypes, types)[source]

Compute the variance of a trace, divided by types.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • ntypes (int) – Number of different types.

  • types (ndarray | list) – Array indicating the type of each element.

Returns:

Array containing the variance values for each type.

Return type:

ndarray

Example

>>> var_by_type = mtrace_var(trace, 2, types)
mtrace_count(trace, ntypes, types)[source]

Count elements per type in a trace.

Parameters:
  • trace (ndarray | list) – Array of trace values.

  • ntypes (int) – Number of different types.

  • types (ndarray | list) – Array indicating the type of each element.

Returns:

Array containing counts for each type.

Return type:

ndarray

Example

>>> counts = mtrace_count(trace, 2, types)
mtrace_sigma(T, L)[source]

Compute one-step class transition probabilities from a marked trace.

Computes P(C_k = j | C_{k-1} = i) empirically from the trace.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times (unused, for API consistency)

  • L (ndarray | list) – Array of class labels

Returns:

C x C matrix where element (i,j) is the probability of observing class j after class i.

Return type:

ndarray

mtrace_sigma2(T, L)[source]

Compute two-step class transition probabilities from a marked trace.

Computes P(C_k = h | C_{k-1} = j, C_{k-2} = i) empirically.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times (unused, for API consistency)

  • L (ndarray | list) – Array of class labels

Returns:

C x C x C 3D array of transition probabilities.

Return type:

ndarray

mtrace_cross_moment(T, L, k)[source]

Compute the k-th order moment of inter-arrival times between class pairs.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • L (ndarray | list) – Array of class labels

  • k (int) – Order of the moment

Returns:

C x C matrix where element (i,j) is E[T^k | C_{t-1} = i, C_t = j]

Return type:

ndarray

mtrace_forward_moment(T, A, orders, norm=True)[source]

Compute forward moments of a marked trace.

Forward moment for class c is E[T_{k+1}^order | C_k = c].

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • A (ndarray | list) – Array of class labels

  • orders (ndarray | list) – Array of moment orders to compute

  • norm (bool) – If True, normalize by class probability

Returns:

Matrix of shape (C, len(orders)) containing forward moments.

Return type:

ndarray

mtrace_backward_moment(T, A, orders, norm=True)[source]

Compute backward moments of a marked trace.

Backward moment for class c is E[T_k^order | C_k = c].

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • A (ndarray | list) – Array of class labels

  • orders (ndarray | list) – Array of moment orders to compute

  • norm (bool) – If True, normalize by class probability

Returns:

Matrix of shape (C, len(orders)) containing backward moments.

Return type:

ndarray

mtrace_cov(T, A)[source]

Compute lag-1 covariance between classes in a marked trace.

Parameters:
Returns:

C x C matrix of 2x2 covariance matrices.

Return type:

ndarray

mtrace_pc(T, L)[source]

Compute the probability of arrival for each class.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times (unused, for API consistency)

  • L (ndarray | list) – Array of class labels

Returns:

Array of class probabilities.

Return type:

ndarray

mtrace_summary(T, L)[source]

Compute comprehensive summary statistics for a marked trace.

Parameters:
Returns:

  • M: First 5 aggregate moments

  • ACF: Autocorrelation for lags 1-100

  • F1, F2: Forward moments of order 1 and 2

  • B1, B2: Backward moments of order 1 and 2

  • C1, C2: Cross moments of order 1 and 2

  • Pc: Class probabilities

  • Pab: One-step transition probabilities

Return type:

Dictionary containing

mtrace_split(T, L)[source]

Split a multi-class trace into per-class traces.

For each class, computes inter-arrival times between consecutive events of that class.

Parameters:
Returns:

List of arrays, one per class, containing inter-arrival times.

Return type:

list

mtrace_merge(t1, t2)[source]

Merge two traces into a single marked (multi-class) trace.

Parameters:
  • t1 (ndarray | list) – Inter-arrival times of the first trace

  • t2 (ndarray | list) – Inter-arrival times of the second trace

Returns:

  • T: Merged inter-arrival times

  • L: Class labels (1 for t1, 2 for t2)

Return type:

Tuple of (T, L) where

mtrace_joint(T, A, i)[source]

Compute class-dependent joint moments.

Computes E[(X^(a)_j)^i[0] * (X^(a)_{j+1})^i[1]] for all classes a.

Parameters:
Returns:

Array of joint moments, one per class.

Return type:

ndarray

mtrace_moment(T, A, orders, after=False, norm=False)[source]

Compute class-dependent moments of a multi-class trace.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • A (ndarray | list) – Array of class labels

  • orders (ndarray | list) – Array of moment orders to compute

  • after (bool) – If True, compute moments of Bucholz variables (forward) If False, compute moments of Horvath variables (backward)

  • norm (bool) – If True, normalize by class probability

Returns:

Matrix of shape (C, len(orders)) containing moments per class.

Return type:

ndarray

mtrace_moment_simple(T, A, k)[source]

Simple interface to compute k-th order moments per class.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • A (ndarray | list) – Array of class labels

  • k (int) – Order of the moment

Returns:

Array of k-th order moments, one per class.

Return type:

ndarray

mtrace_bootstrap(T, A, n_samples=100, seed=None)[source]

Generate bootstrap samples from a marked trace.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • A (ndarray | list) – Array of class labels

  • n_samples (int) – Number of bootstrap samples to generate

  • seed (int) – Random seed

Returns:

Tuple of (T_boot, A_boot) containing bootstrap samples.

Return type:

Tuple[ndarray, ndarray]

mtrace_iat2counts(T, L, scale)[source]

Compute counting process from marked inter-arrival times.

For each class, counts arrivals in windows of specified scale.

Parameters:
  • T (ndarray | list) – Array of inter-arrival times

  • L (ndarray | list) – Array of class labels

  • scale (float) – Time scale for counting

Returns:

Array of counts per class per window.

Return type:

ndarray

Reinforcement Learning (line_solver.api.rl)

Reinforcement Learning (RL) agents for queueing control.

Native Python implementations of RL agents for queueing network control and optimization.

Key classes:

RLTDAgent: Temporal Difference learning agent RLEnvironment: Queueing network environment

Utilities Module (line_solver.utils)

Mock module that can handle any attribute access

Constants Module (line_solver.constants)

Constants and enumerations for LINE queueing network models.

This module defines the various constants, enumerations, and strategies used throughout LINE for specifying model behavior, including:

  • Scheduling strategies (FCFS, LCFS, PS, etc.)

  • Routing strategies (PROB, RAND, etc.)

  • Node types (SOURCE, QUEUE, SINK, etc.)

  • Job class types (OPEN, CLOSED)

  • Solver types and options

  • Activity precedence types for layered networks

  • Call types and drop strategies

These constants ensure type safety and consistency across the API.

class ActivityPrecedenceType(*values)[source]

Bases: Enum

Types of activity precedence relationships in layered networks.

These specify how activities are ordered and synchronized: - PRE_SEQ: Sequential prerequisite (must complete before) - PRE_AND: AND prerequisite (all must complete before) - PRE_OR: OR prerequisite (any must complete before) - POST_SEQ: Sequential post-condition - POST_AND: AND post-condition - POST_OR: OR post-condition - POST_LOOP: Loop post-condition - POST_CACHE: Cache post-condition

class CallType(*values)[source]

Bases: Enum

Types of calls between tasks in layered networks.

  • SYNC: Synchronous call (caller waits for response)

  • ASYNC: Asynchronous call (caller continues immediately)

  • FWD: Forward call (caller terminates, response goes to caller’s caller)

class DropStrategy(*values)[source]

Bases: Enum

Strategies for handling queue overflow and capacity limits.

  • WaitingQueue: Jobs wait in a waiting queue when capacity is exceeded

  • Drop: Jobs are dropped (lost) when capacity is exceeded

  • BlockingAfterService: Jobs are blocked after service completion

class SignalType(*values)[source]

Bases: Enum

Types of signals for signal classes in G-networks and related models.

NEGATIVE

Removes a job from the destination queue (G-network negative customer)

REPLY

Triggers a reply action

CATASTROPHE

Removes ALL jobs from the destination queue

NEGATIVE = 1
REPLY = 2
CATASTROPHE = 3
class RemovalPolicy(*values)[source]

Bases: Enum

Removal policies for negative signals in G-networks.

RANDOM

Select job uniformly at random from all jobs at the station

FCFS

Remove the oldest job (first arrived)

LCFS

Remove the newest job (last arrived)

RANDOM = 1
class EventType(*values)[source]

Bases: Enum

Types of events in discrete-event simulation.

  • INIT: Initialization event

  • LOCAL: Local processing event

  • ARV: Job arrival event

  • DEP: Job departure event

  • PHASE: Phase transition event in multi-phase processes

  • READ: Cache read event

  • STAGE: Staging area event

READ = 6
class JobClassType(*values)[source]

Bases: Enum

Types of job classes in queueing networks.

  • OPEN: Open class (jobs arrive from outside the system)

  • CLOSED: Closed class (fixed population circulating in the system)

  • DISABLED: Disabled class (not currently active)

class JoinStrategy(*values)[source]

Bases: Enum

Strategies for join node synchronization in fork-join networks.

  • STD: Standard join (wait for all parallel branches)

  • PARTIAL: Partial join (proceed when some branches complete)

  • Quorum: Quorum-based join (wait for minimum number of branches)

  • Guard: Guard condition join (custom completion criteria)

class MetricType(*values)[source]

Bases: Enum

Types of performance metrics that can be computed.

SysDropR = 11
SysPower = 13
Tard = 24
SysTard = 25
class NodeType(*values)[source]

Bases: Enum

Types of nodes in queueing network models.

static from_line(obj)[source]
class ProcessType(*values)[source]

Bases: Enum

Types of stochastic processes for arrivals and service times.

static fromString(obj)[source]
class RoutingStrategy(*values)[source]

Bases: Enum

Strategies for routing jobs between network nodes.

class SchedStrategy(*values)[source]

Bases: Enum

Scheduling strategies for service stations.

EDD = 8
EDF = 9
SRPT = 15
SRPTPRIO = 16
HOL = 17
LCFSPRIO = 25
LCFSPRPRIO = 26
LCFSPIPRIO = 27
FCFSPRPRIO = 28
FCFSPIPRIO = 29
PSJF = 31
FB = 32
LAS = 33
LRPT = 34
SETF = 35
static fromString(obj)[source]
static fromLINEString(sched)[source]
static toID(sched)[source]
class SchedStrategyType(*values)[source]

Bases: Enum

Categories of scheduling strategies by preemption behavior.

class ServiceStrategy(*values)[source]

Bases: Enum

Service strategies defining service time dependence.

class SolverType(*values)[source]

Bases: Enum

Types of solvers available in LINE.

DES = 3
class TimingStrategy(*values)[source]

Bases: Enum

Timing strategies for transitions in Petri nets.

class VerboseLevel(*values)[source]

Bases: Enum

Verbosity levels for LINE solver output.

class PollingType(*values)[source]

Bases: Enum

Polling strategies for polling systems.

static fromString(obj)[source]
class HeteroSchedPolicy(*values)[source]

Bases: Enum

Scheduling policies for heterogeneous multiserver queues.

ORDER = 1
ALIS = 2
ALFS = 3
FAIRNESS = 4
FSF = 5
RAIS = 6
static fromString(obj)[source]
class GlobalConstants[source]

Bases: object

Global constants and configuration for the LINE solver.

Immediate = 1e-14
classmethod getInstance()[source]

Get the singleton instance of GlobalConstants.

classmethod get_instance()

Get the singleton instance of GlobalConstants.

classmethod getVerbose()[source]

Get the current verbosity level.

classmethod get_verbose()

Get the current verbosity level.

classmethod setVerbose(verbosity)[source]

Set the verbosity level for solver output.

classmethod set_verbose(verbosity)

Set the verbosity level for solver output.

classmethod getConstants()[source]

Get a dictionary of all global constants.

classmethod get_constants()

Get a dictionary of all global constants.