Utilities and Constants
Helper functions, constants, and enumerations.
These modules provide utility functions, constants, and example models.
Utility Functions (line_solver.utils)
The utils module contains helper functions for working with LINE models.
Utility functions for LINE queueing network analysis.
This module provides helper functions for working with LINE models and results, including table manipulation, mathematical utilities, and data processing functions.
- tget(df, *args)[source]
Extract specific rows/columns from LINE result tables.
This function filters and selects data from pandas DataFrames containing LINE solver results based on station names, job class names, or other identifiers.
- Parameters:
df (
pandas.DataFrame or IndexedTable) – Input DataFrame or IndexedTable with LINE results.*args – Variable arguments specifying filters (station names, job classes, or other identifiers).
- Returns:
Filtered DataFrame with selected rows and columns.
- Return type:
pandas.DataFrame
Examples
>>> results = solver.avg_table() >>> queue_results = tget(results, 'Queue') >>> class1_results = tget(results, 'Class1')
- circul(c)[source]
Generate a circulant matrix.
Creates a circulant matrix where each row is a cyclic permutation of the previous row. For a scalar input, creates a circulant matrix of size c x c with specific pattern.
- Parameters:
c – Either an integer (size of matrix) or array-like (first row).
- Returns:
The circulant matrix.
- Return type:
Examples
>>> circul(3) # Creates a 3x3 circulant matrix >>> circul([1, 2, 3]) # Creates circulant matrix with [1,2,3] as first row
- class IndexedTable(dataframe)[source]
Bases:
objectEnhanced pandas DataFrame wrapper with object-based filtering.
Wraps a MATLAB table to enable filtering using Station, Node, JobClass, and/or Chain objects, while maintaining full backward compatibility with standard pandas operations.
- Variables:
data (
pd.DataFrame) – The underlying pandas DataFrame
Initialize IndexedTable wrapper.
- Parameters:
dataframe – A pandas DataFrame (typically from solver.avgTable(), etc.)
- Raises:
TypeError – If input is not a pandas DataFrame
- __init__(dataframe)[source]
Initialize IndexedTable wrapper.
- Parameters:
dataframe – A pandas DataFrame (typically from solver.avgTable(), etc.)
- Raises:
TypeError – If input is not a pandas DataFrame
- __getattr__(name)[source]
Delegate attribute access to the underlying DataFrame.
Columns are accessible as attributes (table.QLen, table.Util, …) and any other DataFrame attribute/method (iterrows, to_string, values, …) is forwarded so IndexedTable is a drop-in for standard pandas usage.
- __getitem__(key)[source]
Support direct indexing with objects: table[queue, jobclass]
- Parameters:
key – Either a single object/tuple of objects for filtering, or standard pandas indexing (int, slice, list, etc.)
- Returns:
Filtered result or standard pandas indexing result
- Return type:
pd.DataFrame
- filterBy(*args)[source]
Filter table by Station/Node and/or JobClass/Chain objects.
Intelligently filters based on table structure and object types.
- Parameters:
*args – 1 or 2 arguments - Station/Node/JobClass/Chain objects
- Returns:
Filtered DataFrame
- Return type:
pd.DataFrame
- Raises:
ValueError – If invalid argument types or counts provided
- get(*args)[source]
Alias for filterBy - convenient shorthand syntax.
- Parameters:
*args – Same as filterBy
- Returns:
Filtered DataFrame
- Return type:
pd.DataFrame
- tget(*args)[source]
Alias for filterBy - backward compatibility with tget() function.
- Parameters:
*args – Same as filterBy
- Returns:
Filtered DataFrame
- Return type:
pd.DataFrame
- tabulate()[source]
The underlying DataFrame.
Callers written before this wrapper existed test isinstance(t, DataFrame) and fall back to t.tabulate(), so a table that is neither raises inside pandas’ own __getattr__ with a message naming DataFrame rather than this class. Kept as the escape hatch that contract expects; .data is the same object under its current name.
- to_string(index=False, **kwargs)[source]
MATLAB-style rendering, so print(t) and print(t.to_string()) agree.
WITHOUT THIS, to_string fell through __getattr__ to pandas, which formats to display.precision DECIMAL PLACES (5, set in __init__.py) while every other codebase prints 5 SIGNIFICANT DIGITS. The two coincide only for values of order 1: a cache hit rate of 0.024273 printed as 0.02427, one digit short, and the parity comparator read a 1.2e-4 relative gap against MATLAB’s 0.024273 where the underlying values agreed to twelve digits. It looked like a solver defect and was a formatter.
A caller that explicitly wants the index, or passes any other pandas option, gets pandas’ own rendering: this override exists to fix the DEFAULT, not to reimplement DataFrame.to_string.
- property shape
Return shape of underlying DataFrame.
- property columns
Return columns of underlying DataFrame.
- property index
Return index of underlying DataFrame.
Constants and Enumerations (line_solver.constants)
The constants module defines enumerations and global constants used throughout
the LINE Solver package.
Scheduling Strategies
- class SchedStrategy(*values)[source]
Bases:
EnumScheduling strategies for service stations.
Values match lang/base.py SchedStrategy for consistency.
- LCFSPI = 3
- HOL = 9
- LPS = 17
- SETF = 18
- FCFSPR = 22
- EDF = 23
- JOIN = 25
- EDD = 27
- SRPT = 28
- SRPTPRIO = 29
- LCFSPRIO = 30
- LCFSPRPRIO = 31
- LCFSPIPRIO = 32
- FCFSPRPRIO = 33
- FCFSPIPRIO = 34
- PSJF = 36
- FB = 37
- LAS = 38
- LRPT = 39
- FSP = 40
- PAS = 41
- OI = 42
- FCFSPI = 43
Distribution and Process Types
- class ProcessType(*values)[source]
Bases:
EnumTypes of stochastic processes for arrivals and service times.
- BMAP = 22
- MMAP = 23
- DUNIFORM = 24
- BERNOULLI = 25
- PRIOR = 26
- GEOMETRIC = 27
- ME = 28
- RAP = 29
- DISCRETESAMPLER = 30
- ZIPF = 31
- DMAP = 32
- EMPIRICALCDF = 33
- NHPP = 34
- MAPT = 35
- PHT = 36
- MPH = 37
- MMAPT = 38
- MPHT = 39
- BMMAPT = 40
- static isMarkovian(t)[source]
True when
sn.proccarries an exact matrix representation of a process of typet: a genuine (D0, D1) pair, or its matrix-exponential analogue for ME/RAP.The distinction is about
sn.proc, NOT about whatgetProcessreturns.getProcesshands back raw distribution PARAMETERS for several non-Markovian families – Gamma, Weibull, Lognormal, Pareto and Uniform return two scalars (Pareto{alpha, k}, Uniform{min, max}) – and the network refresh replaces those withmap_erlang(mean, n)before storing them insn.proc, wheren = ceil(1/SCV)capped at 100 (n = 20whenSCV < CoarseTol). That fit matches the mean, and matches the SCV only whenSCV <= 1: Pareto with SCV 64 givesn = 1, a single exponential of SCV 1. So for these typessn.procis an approximation, not the law that was requested, and nothing on the cell says so – the only signal issn.procid.Solvers that read
sn.procas if it were the exact law must gate on this predicate. It is the procid-level counterpart of the JAR’sDistribution.isMarkovian(), i.e. of the Markovian class hierarchy, so the two lists must stay in step.
- static isMarked(t)[source]
True when the type carries PER-MARK arrival blocks, i.e. an event of this process is labelled and the label is meaningful to the model. At a Source the label selects the class of the arriving job (
Source.set_marked_arrival,sn.markidx).
- static isMarkedStationary(t)[source]
True when
sn.procholds the STATIONARY marked cell, the M3A layout{D0, D1agg, D11, ..., D1K}.MPH is the renewal special case of MMAP and lowers to exactly that cell (
D0 = S,D1k = s_k*alpha), so every consumer that reads the M3A layout serves both and must gate on this predicate rather than on equality with MMAP.
- static isMarkedSchedule(t)[source]
True when
sn.procholds the MARKED SCHEDULE slot{breakpoints, D0segs, D1aggsegs, cyclic, markSegs}.MPHt is stored lowered to MMAPt form segment by segment, so one walk serves both, exactly as one MAPt walk serves MAPt and PHt.
BMMAPT IS INCLUDED, and its slot is that one with the batch blocks appended, so a consumer gated on this predicate reads a BMMAPt as the MMAPt it aggregates down to. That is right for anything time-blind or batch-blind and WRONG for anything that releases jobs: an arrival or service sampler must branch on
isBatch()as well, or it silently delivers one job per epoch.
- static isBatch(t)[source]
True when an EVENT of this process releases (or, as a service process, completes) a BATCH of jobs whose size the process itself carries in its blocks.
This is the batch twin of
isMarkedStationary()andisMarkedSchedule(), and the same rule applies: a procid test that should serve every batch family is a MEMBERSHIP test, never equality with BMAP.It is disjoint from
sn.arrivalbatch, which is a SEPARATE batch-size law bolted onto a renewal stream bySource.set_arrival_batch. A process that is isBatch already carries its own sizes, so the two are mutually exclusive by construction.
Node Types
Job Class Types
Routing Strategies
Service Strategies
Solver Types
Metric Types
Drop and Replacement Strategies
- class DropStrategy(*values)[source]
Bases:
EnumStrategies for handling queue overflow and capacity limits.
WaitingQueue: Jobs wait in a waiting queue when capacity is exceeded
Queue: Alias for WaitingQueue
Drop: Jobs are dropped (lost) when capacity is exceeded
BlockingAfterService: Jobs are blocked after service completion
BlockingBeforeService: Jobs are blocked before service starts
ReServiceOnRejection: Rejected jobs are re-served at the upstream station
Values match the MATLAB DropStrategy constants and the JAR jline.lang.constant.DropStrategy ids, which are the interchange encoding of sn.droprule and sn.regionrule. Keep the three Python definitions of this enum (here, lang/base.py, api/sn/network_struct.py) numerically identical: they are written and read by different modules over the same sn fields.
- BlockingBeforeService = 3
- ReServiceOnRejection = 4
- class ReplacementStrategy(*values)[source]
Bases:
IntEnumCache replacement strategies.
Determines which item to evict when the cache is full and a new item needs to be stored.
- Variables:
RR – Random Replacement - evict a random item
FIFO – First-In-First-Out - evict oldest item
SFIFO – Strict FIFO - FIFO eviction, no reinsertion/promotion on hit
LRU – Least Recently Used - evict least recently accessed item
- HLRU = 4
- CLIMB = 5
- QLRU = 6
Join Strategies
- class JoinStrategy(*values)[source]
Bases:
IntEnumEnumeration of join strategies.
PARTIAL is the canonical name of the k-of-n join, as in the MATLAB JoinStrategy class, so that .name serializes straight to the interchange spelling; QUORUM is kept as an alias for it because that is how the JAR (jline.lang.constant.JoinStrategy.Quorum) spells the same strategy. Only the names cross codebases, in the JSON joinStrategy field and the .lqnx path; the numeric values are compared solely against this enum, so they need not match the MATLAB or JAR ids.
- QUORUM = 1
- CANDJOIN = 2
Layered Network Types
- class CallType(*values)[source]
Bases:
EnumTypes 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 ActivityPrecedenceType(*values)[source]
Bases:
EnumTypes 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
Polling Types
Event and Timing Types
- class EventType(*values)[source]
Bases:
EnumTypes 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
- ENABLE = 8
- FIRE = 9
- PRE = 10
- POST = 11
- RENEGE = 12
- RETRY = 13
- SWITCH = 14
- FAILURE = 15
- REPAIR = 16
- START = 17
- PREEMPT = 18
Verbose Level
Global Constants
- class GlobalConstants[source]
Bases:
objectGlobal constants and configuration for the LINE solver.
- ArcTol = 1e-12
- Immediate = 100000000.0
- classmethod isLibraryAttributionShown()[source]
True if the library attribution has already been printed.
- classmethod setLibraryAttributionShown(value=True)[source]
Record that the library attribution has been printed.
- classmethod get_instance()
Get the singleton instance of GlobalConstants.
- classmethod get_verbose()
Get the current verbosity level.
- classmethod set_verbose(verbosity)
Set the verbosity level for solver output.
- classmethod get_constants()
Get a dictionary of all global constants.
Example Gallery (line_solver.gallery)
The gallery module provides a collection of example queueing models for
validation, testing, and learning purposes.
- gallery_aphm1()[source]
Create an APH/M/1 queueing model.
Models a single-server queue with Acyclic Phase-type (APH) arrivals and exponential service times. Demonstrates advanced arrival process modeling.
- Returns:
APH/M/1 queueing network model.
- Return type:
- gallery_coxm1()[source]
Create a Cox/M/1 queueing model.
Models a single-server queue with Coxian arrivals (fitted to high variability) and exponential service times. Used for modeling bursty arrival processes.
- Returns:
Cox/M/1 queueing network model with SCV=4.0 arrivals.
- Return type:
- gallery_detm1()[source]
Create a D/M/1 queueing model.
Models a single-server queue with deterministic (constant) arrivals and exponential service times. Classic model for studying the effect of deterministic arrivals on queueing performance.
- Returns:
D/M/1 queueing network model.
- Return type:
- gallery_erlm1()[source]
Create an Erlang/M/1 queueing model.
Models a single-server queue with 5-phase Erlang arrivals and exponential service times. Demonstrates low-variability arrival processes with coefficient of variation < 1.
- Returns:
Er/M/1 queueing network model with 5-phase Erlang arrivals.
- Return type:
- gallery_erlm1ps()[source]
Create an Erlang/M/1 queue with Processor Sharing.
Models a single-server queue with 5-phase Erlang arrivals, exponential service times, and processor sharing scheduling. Demonstrates PS scheduling with controlled-variance arrivals.
- Returns:
Er/M/1-PS queueing network model.
- Return type:
- gallery_gamm1()[source]
Create a Gamma/M/1 queueing model.
Models a single-server queue with Gamma-distributed arrivals and exponential service times. Uses Gamma distribution fitted to mean=1, SCV=0.2 for flexible arrival process modeling.
- Returns:
Gamma/M/1 queueing network model.
- Return type:
- gallery_hyperlk(k=2)[source]
Create a HyperExp/Erlang/k queueing model.
Models a multi-server queue with high-variability hyper-exponential arrivals and low-variability Erlang service times. Demonstrates the interaction between high-variance arrivals and controlled-variance service.
- gallery_hypm1()[source]
Create a HyperExp/M/1 queueing model.
Models a single-server queue with extremely high-variability hyper-exponential arrivals (SCV=64) and exponential service times. Demonstrates modeling of very bursty arrival processes.
- Returns:
H/M/1 queueing network model with very high-variance arrivals.
- Return type:
- gallery_mm1_linear(n=2, Umax=0.9)[source]
Create a linear tandem network of M/M/1 queues.
Models a series of single-server queues in tandem, with utilizations that form a pattern (increasing then decreasing). Used for studying the behavior of jobs flowing through multiple service stages.
- gallery_mm1_tandem()[source]
Create a simple 2-queue M/M/1 tandem network.
Convenience function that creates a 2-queue linear tandem network by calling gallery_mm1_linear(2). Represents the basic tandem queueing system.
- Returns:
2-queue M/M/1 tandem network.
- Return type:
- gallery_mmk(k=2)[source]
Create an M/M/k multi-server queueing model.
Models a multi-server queue with Poisson arrivals, exponential service times, and k identical servers. Demonstrates the performance benefits of multiple servers versus a single fast server.
- gallery_mpar1()[source]
Create an M/Pareto/1 queueing model.
Models a single-server queue with Poisson arrivals and heavy-tailed Pareto-distributed service times. Demonstrates modeling of service processes with very high variability and infinite variance.
- Returns:
M/Par/1 queueing network model with Pareto service times.
- Return type:
- gallery_parm1()[source]
Create a Pareto/M/1 queueing model.
Models a single-server queue with heavy-tailed Pareto arrivals and exponential service times. Demonstrates modeling of bursty arrival processes with power-law characteristics.
- Returns:
Par/M/1 queueing network model with Pareto arrivals.
- Return type:
- gallery_um1()[source]
Create a Uniform/M/1 queueing model.
Models a single-server queue with uniformly distributed arrivals and exponential service times. Demonstrates modeling with bounded inter-arrival times.
- Returns:
U/M/1 queueing network model with uniform arrivals.
- Return type:
- gallery_cqn(M=2, useDelay=False, seed=2300)[source]
Create a closed queueing network (CQN) model.
Models a closed network with fixed population, where jobs circulate between service stations. Can use either delay stations (infinite servers) or finite capacity queues depending on the useDelay parameter.
- gallery_mm1_feedback(p=0.5)[source]
Create an M/M/1 queue with probabilistic feedback.
Models a single-server queue where jobs have probability p of returning to the queue after service completion, creating a feedback loop. This increases the effective service demand and response time.
- gallery_mm1_prio()[source]
Create an M/M/1 queue with priority classes.
Models a single-server queue with two job classes having different priorities. High priority jobs are served before low priority jobs, demonstrating head-of-line priority scheduling.
- Returns:
M/M/1 queueing network with high and low priority classes.
- Return type:
- gallery_mm1_multiclass()[source]
Create an M/M/1 queue with multiple job classes.
Models a single-server queue with two different job classes arriving from separate sources, each with different arrival rates and service requirements. Demonstrates multi-class queueing behavior.
- Returns:
M/M/1 multi-class queueing network model.
- Return type:
- gallery_mapm1(map_arrival=None)[source]
Create a MAP/M/1 queueing model with Markovian arrival process.
Models a single-server queue with a Markovian Arrival Process (MAP) and exponential service times. MAP allows modeling of correlated arrivals and more complex arrival patterns than Poisson processes.
- Parameters:
map_arrival – MAP arrival process (default: None, creates a standard MAP).
- Returns:
MAP/M/1 queueing network model.
- Return type:
- gallery_multitier()[source]
Create a 4-tier J2EE Layered Queueing Network (client/app/database).
Reference LQN with multiple entries per task and or-fork/or-join activity precedence. Ported from MATLAB gallery_multitier.
- Returns:
3-layer (client, application, database) LQN model.
- Return type:
- gallery_multitier_storage()[source]
Create a 4-tier J2EE LQN with a dedicated cache layer (LRU replacement).
Extends gallery_multitier with a cache layer (CacheTask + ItemEntry) and cache-access hit/miss precedence. Ported from MATLAB gallery_multitier_storage.
- Returns:
4-layer LQN model with cache layer.
- Return type:
- gallery_fj_quorum()[source]
Closed fork-join network with a 2-of-3 quorum join.
The join fires on the SECOND of the three sibling tasks; the third is discarded when it arrives. SolverLDES and SolverJMT reproduce it exactly; SolverMVA and SolverNC charge the second order statistic of the branch completion times (fj_ordstat_exp).
- gallery_lqn_workflows()[source]
Layered network with loop, and-fork/join and or-fork/join precedence.
- gallery_fcr(K=3)[source]
Finite capacity region with dropping around a single queue (like M/M/1/K).
- gallery_renv_breakdown()[source]
Random environment: single server with breakdown/repair (UP/DOWN stages).
Returns an Environment whose base model is an M/M/1 queue alternating between an UP stage (fast service) and a DOWN stage (degraded service).
- gallery_qn_random(seed=23000)[source]
Randomly generated mixed queueing network (reproducible).
Uses NetworkGenerator with a deterministic (cyclic) topology and a fixed default seed so repeated calls yield the same model. Closed network: 3 queues, 1 delay, 2 closed classes (always stable / solvable).