Source code for line_solver.api.polling.polling

"""
Polling System Analysis Algorithms.

Native Python implementations for analyzing polling/vacation queue systems
with various disciplines including exhaustive, gated, and 1-limited.

References:
    Takagi, H., "Queuing analysis of polling models: An update."
    ACM Computing Surveys, Vol. 20, No. 1, March 1988.
"""

import numpy as np
from scipy import linalg
from typing import List, Tuple, Union

# Import MAP functions from our native MAM module
from ..mam import map_lambda, map_mean, map_moment, map_var
from line_solver.api.io.errors import LineNumericalError, LineUnsupportedError, LineUnsupportedValueError, LineNumericalValueError


def _polling_moments(arvMAPs, svcMAPs, switchMAPs):
    """Reduce the per-queue descriptors to the moments Takagi's formulas read.

    Mirrors MATLAB api/polling/private/polling_moments.m. Each entry is either a
    MAP ``(D0, D1)`` or a NUMERIC moment form, given as a float or a 1-D numpy
    array:
      arvMAPs[i]    MAP, or the arrival rate lambda_i
      svcMAPs[i]    MAP, or [E[S_i], E[S_i^2]]
      switchMAPs[i] MAP, or [E[R_i], Var[R_i]]
    The numeric form lets a solver pass a law that has no MAP, e.g. a
    deterministic switchover (variance zero), exactly rather than through an
    exponential surrogate of the wrong variance.
    """
    def numeric(x):
        return np.isscalar(x) or (isinstance(x, np.ndarray) and x.ndim <= 1)

    n = len(arvMAPs)
    lam = np.zeros(n); b = np.zeros(n); b2 = np.zeros(n)
    r1 = np.zeros(n); delta2 = np.zeros(n)
    for i in range(n):
        a = arvMAPs[i]
        lam[i] = float(np.ravel(a)[0]) if numeric(a) else map_lambda(a[0], a[1])
        sv = svcMAPs[i]
        if numeric(sv):
            b[i], b2[i] = float(np.ravel(sv)[0]), float(np.ravel(sv)[1])
        else:
            b[i] = map_mean(sv[0], sv[1])
            b2[i] = map_moment(sv[0], sv[1], 2)
        sw = switchMAPs[i]
        if numeric(sw):
            r1[i], delta2[i] = float(np.ravel(sw)[0]), float(np.ravel(sw)[1])
        else:
            r1[i] = map_mean(sw[0], sw[1])
            delta2[i] = map_var(sw[0], sw[1])
    return lam, b, b2, r1, delta2


[docs] def polling_qsys_exhaustive( arvMAPs: List[Tuple[np.ndarray, np.ndarray]], svcMAPs: List[Tuple[np.ndarray, np.ndarray]], switchMAPs: List[Tuple[np.ndarray, np.ndarray]] ) -> np.ndarray: """ 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). Args: arvMAPs: Per-queue arrival MAPs (D0, D1), or arrival rates. svcMAPs: Per-queue service MAPs (D0, D1), or [E[S], E[S^2]] arrays. switchMAPs: Per-queue switchover MAPs (D0, D1), or [E[R], Var[R]] arrays; the switchover of queue i is the walk OUT of it. See _polling_moments for the numeric form. Returns: Array of mean waiting times for each queue. """ n = len(arvMAPs) lambda_arr, b, b2, r1, delta2 = _polling_moments(arvMAPs, svcMAPs, switchMAPs) rho1 = lambda_arr * b rho = float(np.sum(rho1)) r = float(np.sum(r1)) # Build system of equations lst1 = [] lst2 = [] for i in range(1, n + 1): # 1-indexed for j in range(1, n + 1): if i > j: t1 = np.zeros(n * n) for m in range(i + 1, n + 1): t1[(j - 1) * n + m - 1] -= 1 for m in range(1, j): t1[(j - 1) * n + m - 1] -= 1 for m in range(j, i): t1[(m - 1) * n + j - 1] -= 1 t1[(i - 1) * n + j - 1] += (1 - rho1[i - 1]) / rho1[i - 1] lst1.append(t1) lst2.append(0.0) elif j > i: t1 = np.zeros(n * n) for m in range(i + 1, j): t1[(j - 1) * n + m - 1] -= 1 for m in range(j, n + 1): t1[(m - 1) * n + j - 1] -= 1 for m in range(1, i): t1[(m - 1) * n + j - 1] -= 1 t1[(i - 1) * n + j - 1] += (1 - rho1[i - 1]) / rho1[i - 1] lst1.append(t1) lst2.append(0.0) else: # i == j t1 = np.zeros(n * n) t1[(i - 1) * n + i - 1] += 1 for m in range(1, n + 1): if i != m: t1[(i - 1) * n + m - 1] -= rho1[i - 1] / (1 - rho1[i - 1]) lst1.append(t1) temp = 0.0 idx = i - 2 if i > 1 else n - 1 temp += delta2[idx] / (1 - rho1[i - 1])**2 temp += (lambda_arr[i - 1] * b2[i - 1] * r * (1 - rho1[i - 1]) / ((1 - rho) * (1 - rho1[i - 1])**3)) lst2.append(temp) # Solve linear system size = len(lst1) A = np.array(lst1) # Shape: (size, n*n) B = np.array(lst2) # Shape: (size,) try: x = linalg.lstsq(A, B)[0] except linalg.LinAlgError: # SVD did not converge x = np.zeros(n * n) # Compute waiting times W = np.zeros(n) for i in range(1, n + 1): temp = lambda_arr[i - 1] * b2[i - 1] / (2 * (1 - rho1[i - 1])) temp += r * (1 - rho1[i - 1]) / (2 * (1 - rho)) sum_val = 0.0 for j in range(1, n + 1): if i != j: sum_val += x[(i - 1) * n + j - 1] sum_val *= (1 - rho1[i - 1]) / rho1[i - 1] idx = i - 2 if i > 1 else n - 1 sum_val += delta2[idx] sum_val /= r * (1 - rho1[i - 1]) * 2 / (1 - rho) temp += sum_val W[i - 1] = temp return W
[docs] def polling_qsys_gated( arvMAPs: List[Tuple[np.ndarray, np.ndarray]], svcMAPs: List[Tuple[np.ndarray, np.ndarray]], switchMAPs: List[Tuple[np.ndarray, np.ndarray]] ) -> np.ndarray: """ 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). Args: arvMAPs: Per-queue arrival MAPs (D0, D1), or arrival rates. svcMAPs: Per-queue service MAPs (D0, D1), or [E[S], E[S^2]] arrays. switchMAPs: Per-queue switchover MAPs (D0, D1), or [E[R], Var[R]] arrays; the switchover of queue i is the walk OUT of it. See _polling_moments for the numeric form. Returns: Array of mean waiting times for each queue. """ n = len(arvMAPs) lambda_arr, b, b2, r1, delta2 = _polling_moments(arvMAPs, svcMAPs, switchMAPs) rho1 = lambda_arr * b rho = float(np.sum(rho1)) r = float(np.sum(r1)) # Build system of equations lst1 = [] lst2 = [] for i in range(n): # 0-indexed for j in range(n): if i > j: t1 = np.zeros(n * n) for m in range(i, n): t1[j * n + m] = -1.0 for m in range(0, j): t1[j * n + m] = -1.0 for m in range(j, i): t1[m * n + j] = -1.0 t1[i * n + j] = 1 / rho1[i] lst1.append(t1) lst2.append(0.0) elif j > i: t1 = np.zeros(n * n) for m in range(i, j): t1[j * n + m] = -1.0 for m in range(j, n): t1[m * n + j] = -1.0 for m in range(0, i): t1[m * n + j] = -1.0 t1[i * n + j] = 1 / rho1[i] lst1.append(t1) lst2.append(0.0) else: # i == j t1 = np.zeros(n * n) t1[i * n + i] += 1 for m in range(n): if i != m: t1[i * n + m] = -rho1[i] for m in range(n): t1[m * n + i] -= rho1[i] * rho1[i] lst1.append(t1) temp = delta2[i] + lambda_arr[i] * b2[i] * r / (1 - rho) lst2.append(temp) # Solve linear system n1 = len(lst1) A = np.array(lst1) B = np.array(lst2) try: x = linalg.lstsq(A, B)[0] except linalg.LinAlgError: # SVD did not converge x = np.zeros(n * n) # Compute waiting times W = np.zeros(n) for i in range(n): temp = (1 + rho1[i]) * r / (2 * (1 - rho)) sum_val = 0.0 for j in range(n): if i != j: sum_val += x[i * n + j] sum_val *= (1 / rho1[i]) for j in range(n): sum_val += x[j * n + i] temp += (1 - rho) * (1 + rho1[i]) * sum_val / (2 * r) W[i] = temp return W
[docs] def polling_qsys_1limited( arvMAPs: List[Tuple[np.ndarray, np.ndarray]], svcMAPs: List[Tuple[np.ndarray, np.ndarray]], switchMAPs: List[Tuple[np.ndarray, np.ndarray]] ) -> np.ndarray: """ Compute approximate mean waiting times for a 1-limited polling system. In 1-limited polling, the server serves at most one customer from each queue before moving to the next queue. Boxma-Meister approximation (SIGMETRICS/PERFORMANCE '86), as reported by Takagi, ACM Computing Surveys, Vol. 20, No. 1, 1988. No exact closed form exists for asymmetric 1-limited systems; the formula is exact for symmetric ones. The last bracket term sums rho_j(1+rho_j) over ALL queues. Args: arvMAPs: Per-queue arrival MAPs (D0, D1), or arrival rates. svcMAPs: Per-queue service MAPs (D0, D1), or [E[S], E[S^2]] arrays. switchMAPs: Per-queue switchover MAPs (D0, D1), or [E[R], Var[R]] arrays; the switchover of queue i is the walk OUT of it. See _polling_moments for the numeric form. Returns: Array of mean waiting times for each queue. """ n = len(arvMAPs) lambda_arr, b, b2, r1, delta2 = _polling_moments(arvMAPs, svcMAPs, switchMAPs) rho1 = lambda_arr * b rho = float(np.sum(rho1)) r = float(np.sum(r1)) d = float(np.sum(delta2)) # Compute waiting times using closed-form formula W = np.zeros(n) sum_of_squares = np.sum(rho1**2) sum_product = np.sum(lambda_arr * b2) for i in range(n): # Queue i is stable while rho + lambda_i r < 1. Past the boundary the formula turns negative, but the wait diverges. if 1 - rho - lambda_arr[i] * r <= 0: W[i] = np.inf continue W[i] = (1 - rho + rho1[i]) / (1 - rho - lambda_arr[i] * r) W[i] *= (1 - rho) / ((1 - rho) * rho + sum_of_squares) W[i] *= (rho / (2 * (1 - rho)) * sum_product + rho * d / 2 / r + r / (2 * (1 - rho)) * np.sum(rho1 * (1 + rho1))) return W
[docs] def polling_qsys_decrementing( arvMAPs: List[Tuple[np.ndarray, np.ndarray]], svcMAPs: List[Tuple[np.ndarray, np.ndarray]], switchMAPs: List[Tuple[np.ndarray, np.ndarray]] ) -> np.ndarray: """ Compute mean waiting times for a decrementing (semiexhaustive) polling system with open (Poisson) arrivals. In decrementing service, the server serves a queue until the number of jobs present drops to one less than the number found at the polling instant. The symmetric system admits the exact closed form of Pittel (1973) and Takagi (1984); see Takagi, ACM Computing Surveys, Vol. 20, No. 1, 1988, eq (28). No exact closed form for the individual E[W_i] is known for asymmetric decrementing systems. There an approximation is returned: E[W_i] = c*f_i with f_i = (1-rho_i)/(1-rho-lambda_i(1-rho_i)R), R the total switchover time, and c chosen so that the W satisfy the exact pseudo-conservation law (see polling_pcl). It is exact for symmetric systems; against the exact CTMC of two- and three-queue exponential systems its error was within about 15%. Args: arvMAPs: Per-queue arrival MAPs (D0, D1), or arrival rates. svcMAPs: Per-queue service MAPs (D0, D1), or [E[S], E[S^2]] arrays. switchMAPs: Per-queue switchover MAPs (D0, D1), or [E[R], Var[R]] arrays; the switchover of queue i is the walk OUT of it. See _polling_moments for the numeric form. Returns: Array of mean waiting times for each queue. """ n = len(arvMAPs) lambda_arr, b, b2, r1, delta2 = _polling_moments(arvMAPs, svcMAPs, switchMAPs) # The exact result of Takagi (1984) requires a symmetric system. def _reldiff(x, y): scale = max(abs(x), abs(y)) return 0.0 if scale < 1e-30 else abs(x - y) / scale tol = 1e-6 for i in range(1, n): if (_reldiff(lambda_arr[i], lambda_arr[0]) > tol or _reldiff(b[i], b[0]) > tol or _reldiff(b2[i], b2[0]) > tol or _reldiff(r1[i], r1[0]) > tol or _reldiff(delta2[i], delta2[0]) > tol): return _decrementing_asymmetric(lambda_arr, b, b2, r1, delta2) N = float(n) lam = lambda_arr[0] b2s = b2[0] r = r1[0] d2 = delta2[0] rho = N * lam * b[0] denom = 2.0 * (1.0 - rho - lam * r * (N - rho)) if denom <= 0.0: raise LineNumericalValueError( "Decrementing polling system is unstable: " "rho + lambda*r*(N-rho) >= 1.", error_id='LINE:numerical:Instability') residual_switchover = d2 / (2.0 * r) if r > 0.0 else 0.0 Wval = residual_switchover + ( N * lam * b2s * (1.0 - lam * r) + (r + lam * d2) * (N - rho)) / denom return Wval * np.ones(n)
__all__ = [ 'polling_qsys_exhaustive', 'polling_qsys_gated', 'polling_qsys_1limited', 'polling_qsys_decrementing', 'polling_pcl', ] def _numeric_form(x): """A list or tuple of plain numbers is the numeric moment form; turn it into the 1-D array _polling_moments recognizes (a MAP stays a pair of matrices).""" if isinstance(x, (list, tuple)) and len(x) > 0 and all(np.isscalar(v) for v in x): return np.asarray(x, dtype=float) return x
[docs] def polling_qsys_table(arvMAPs, svcMAPs, switchMAPs, table, discipline): """Exact mean waiting times of a polling system with a POLLING TABLE. Mirrors MATLAB api/polling/polling_qsys_table.m. Open Poisson arrivals; the server visits the queues in the order table[0], table[1], ..., cyclically (Haverkort section 9.1.2), every queue appearing at least once and possibly several times. All queues are served exhaustively or all gated. Args: arvMAPs: per queue, a MAP (D0, D1) or the arrival rate (reduced to its rate: arrivals must be Poisson). svcMAPs: per queue, a MAP or [E[S], E[S^2]]. switchMAPs: one entry PER TABLE POSITION, the switchover of the leg from position m to position m+1 (the last closing the cycle): a MAP or [E[R], Var[R]]. table: 1-based queue indices, e.g. [1, 2, 1, 3] (MATLAB convention). discipline: 'exhaustive' or 'gated' (or a PollingType). Method (buffer occupancy, Eisenberg 1972): the first and second moments of the queue lengths at the polling instants obey an affine recursion over the table positions, of dimension n + n^2; the cycle-stationary moment vector solves its fixed point and is propagated to every position. Then exhaustive W_i = lambda_i b2_i/(2(1-rho_i)) + sum_m E[X_i(X_i-1)]_m / (2 lambda_i sum_m E[X_i]_m) gated W_i = (1+rho_i) sum_m E[X_i(X_i-1)]_m / (2 lambda_i sum_m E[X_i]_m) the sums running over the positions m of queue i. For table = 1..n this is the classical cyclic system (Takagi 1988, eqs. 15 and 21). Returns: (W, EX, EX2): W[i] the mean waiting time of queue i, EX[m, :] = E[X] and EX2[m] = E[X X'] at the polling instant of position m. """ from line_solver.constants import PollingType from line_solver.api.io.errors import LineInputError arvMAPs = [_numeric_form(a) for a in arvMAPs] svcMAPs = [_numeric_form(s) for s in svcMAPs] switchMAPs = [_numeric_form(s) for s in switchMAPs] n = len(arvMAPs) table = [int(t) for t in np.ravel(np.asarray(table))] M = len(table) if len(switchMAPs) != M: raise LineInputError('polling_qsys_table needs one switchover per table position (%d).' % M, error_id='LINE:input:Argument') if any(t < 1 or t > n for t in table) or any((i + 1) not in table for i in range(n)): raise LineInputError('The polling table must list every queue 1..%d at least once.' % n, error_id='LINE:input:Argument') if isinstance(discipline, str): d = discipline.lower() if d == 'exhaustive': gated = False elif d == 'gated': gated = True else: raise LineInputError("The discipline must be 'exhaustive' or 'gated'.", error_id='LINE:input:Argument') else: if discipline == PollingType.EXHAUSTIVE: gated = False elif discipline == PollingType.GATED: gated = True else: raise LineUnsupportedError('polling_qsys_table is exact for exhaustive or gated service only.', error_id='LINE:unsupported:SchedStrategy_POLLING') # _polling_moments reads one switchover per queue: reduce the per-position # legs separately lam, b, b2, _, _ = _polling_moments(arvMAPs, svcMAPs, [np.zeros(2)] * n) s1 = np.zeros(M) s2 = np.zeros(M) for m in range(M): _, _, _, r1m, svm = _polling_moments(arvMAPs[:1], svcMAPs[:1], [switchMAPs[m]]) s1[m] = r1m[0] s2[m] = svm[0] + r1m[0] ** 2 if np.any(lam <= 0): raise LineInputError('polling_qsys_table needs a positive arrival rate at every queue.', error_id='LINE:input:Argument') rho1 = lam * b if np.sum(rho1) >= 1: raise LineNumericalError('The polling system is unstable: rho >= 1.', error_id='LINE:numerical:Instability') if np.all(s1 == 0): raise LineInputError('polling_qsys_table needs a positive total switchover time per cycle.', error_id='LINE:input:Argument') # visit period moments per queue if gated: y1 = b.copy() y2 = b2.copy() else: y1 = b / (1 - rho1) y2 = b2 / (1 - rho1) ** 3 N = n + n * n la = lam.reshape(-1, 1) def step(zi, q, m): # visit of queue q at position m followed by the switchover leg m mu = zi[:n].reshape(-1, 1) S = zi[n:].reshape(n, n, order='F') lp = la.copy() if not gated: lp[q] = 0 D = np.eye(n) D[q, q] = 0 EV = y1[q] * mu[q, 0] EV2 = mu[q, 0] * (y2[q] - y1[q] ** 2) + S[q, q] * y1[q] ** 2 mu1 = D @ mu + lp * y1[q] * mu[q, 0] S1 = (D @ S @ D.T + D @ S[:, [q]] * y1[q] @ lp.T + lp * y1[q] @ S[[q], :] @ D.T + (lp @ lp.T) * EV2 + np.diag(lp.ravel()) * EV) mu2 = mu1 + la * s1[m] S2 = (S1 + mu1 @ la.T * s1[m] + la @ mu1.T * s1[m] + (la @ la.T) * s2[m] + np.diag(lam) * s1[m]) return np.concatenate([mu2.ravel(), S2.ravel(order='F')]) A = [] c = [] for m in range(M): q = table[m] - 1 cm = step(np.zeros(N), q, m) Am = np.zeros((N, N)) for k in range(N): e = np.zeros(N) e[k] = 1.0 Am[:, k] = step(e, q, m) - cm A.append(Am) c.append(cm) # cycle map from position 0 back to position 0 Acyc = np.eye(N) ccyc = np.zeros(N) for m in range(M): ccyc = A[m] @ ccyc + c[m] Acyc = A[m] @ Acyc z = [None] * M z[0] = np.linalg.solve(np.eye(N) - Acyc, ccyc) for m in range(M - 1): z[m + 1] = A[m] @ z[m] + c[m] EX = np.zeros((M, n)) EX2 = [] for m in range(M): EX[m, :] = z[m][:n] S = z[m][n:].reshape(n, n, order='F') EX2.append((S + S.T) / 2) W = np.zeros(n) for i in range(n): num = 0.0 den = 0.0 for m in range(M): if table[m] == i + 1: num += EX2[m][i, i] - EX[m, i] den += EX[m, i] resid = num / (2 * lam[i] * den) if gated: W[i] = (1 + rho1[i]) * resid else: W[i] = lam[i] * b2[i] / (2 * (1 - rho1[i])) + resid return W, EX, EX2
[docs] def polling_qsys_klimited(arvMAPs, svcMAPs, switchMAPs, K): """Approximate mean waiting times of a cyclic k-limited polling system. Mirrors MATLAB api/polling/polling_qsys_klimited.m. Queue i is served K_i-limited: a visit ends after K_i services or when the queue empties (arrivals during the visit are eligible, as in SolverCTMC's KLIMITED). The approximation is Fuhrmann's relation for symmetric k-limited systems (Haverkort eq. 9.27; Takagi 1988 eq. 27), E[W_i] + b_i = (1-rho) / (1 - rho - lambda_i R / K_i) (E[W_i^E] + b_i), applied queue by queue, E[W_i^E] being the exact exhaustive mean waiting time of the same system and R the mean total switchover per cycle. Exact in the symmetric case for K=1 and as K grows to infinity. Args: arvMAPs, svcMAPs, switchMAPs: as polling_qsys_exhaustive. K: a positive integer, or one per queue. Raises: LineNumericalError (LINE:numerical:Instability) when rho + lambda_i R / K_i >= 1 at some queue. """ from line_solver.api.io.errors import LineInputError arvMAPs = [_numeric_form(a) for a in arvMAPs] svcMAPs = [_numeric_form(s) for s in svcMAPs] switchMAPs = [_numeric_form(s) for s in switchMAPs] n = len(arvMAPs) Kv = np.ravel(np.asarray(K, dtype=float)) if Kv.size == 1: Kv = Kv[0] * np.ones(n) if Kv.size != n or np.any(Kv < 1) or np.any(Kv != np.round(Kv)): raise LineInputError('K must be a positive integer, or one positive integer per queue.', error_id='LINE:input:Argument') lam, b, _, r1, _ = _polling_moments(arvMAPs, svcMAPs, switchMAPs) rho = float(np.sum(lam * b)) R = float(np.sum(r1)) den = 1 - rho - lam * R / Kv if np.any(den <= 0): raise LineNumericalError('The k-limited polling system is unstable: rho + lambda_i*R/K_i >= 1 at some queue.', error_id='LINE:numerical:Instability') WE = np.asarray(polling_qsys_exhaustive(arvMAPs, svcMAPs, switchMAPs), dtype=float) return (1 - rho) / den * (WE + b) - b
def _decrementing_asymmetric(lam, b, b2, r1, delta2): """PCL-scaled approximation of an asymmetric decrementing system (MATLAB polling_qsys_decrementing.m parity).""" rhoi = lam * b rho = float(np.sum(rhoi)) R = float(np.sum(r1)) den = 1.0 - rho - lam * (1.0 - rhoi) * R if rho >= 1.0 or np.any(den <= 0.0): raise LineNumericalValueError( "Decrementing polling system is unstable: " "rho + lambda_i*(1-rho_i)*R >= 1 for some queue.", error_id='LINE:numerical:Instability') f = (1.0 - rhoi) / den w, rhs = _pcl_terms(lam, b, b2, r1, delta2, 'D' * len(lam)) return rhs / float(np.dot(w, f)) * f def _pcl_terms(lam, b, b2, r1, delta2, code): """Weights and right-hand side of the pseudo-conservation law (MATLAB api/polling/private/polling_pcl_terms.m).""" code = np.array(list(code)) rhoi = lam * b rho = float(np.sum(rhoi)) R = float(np.sum(r1)) D2 = float(np.sum(delta2)) w = rhoi.astype(float).copy() isL = code == 'L' isD = code == 'D' w[isL] = rhoi[isL] * (1.0 - lam[isL] * R / (1.0 - rho)) w[isD] = rhoi[isD] * (1.0 - lam[isD] * (1.0 - rhoi[isD]) * R / (1.0 - rho)) resid = rho * D2 / (2.0 * R) if R > 0 else 0.0 isGL = (code == 'G') | isL rhs = (rho * np.sum(lam * b2) / (2.0 * (1.0 - rho)) + resid + R * (rho - np.sum(rhoi ** 2)) / (2.0 * (1.0 - rho)) + R / (1.0 - rho) * np.sum(rhoi[isGL] ** 2) - R / (2.0 * (1.0 - rho)) * np.sum(rhoi[isD] * lam[isD] ** 2 * b2[isD])) return w, float(rhs) def _pcl_codes(disc, n): """Map disciplines to the PCL classes 'E','G','L' (1-limited),'D' (MATLAB api/polling/private/polling_pcl_codes.m). DISC is a PollingType, a character, a (PollingType, K) tuple, or a list of these, one per queue.""" from line_solver.constants import PollingType def one(d): K = 1 if isinstance(d, tuple): d, K = d if isinstance(d, str): c = d[:1].upper() else: c = {PollingType.EXHAUSTIVE: 'E', PollingType.GATED: 'G', PollingType.KLIMITED: 'L', PollingType.GLIMITED: 'L', PollingType.DECREMENTING: 'D'}.get(d, '?') if c not in ('E', 'G', 'L', 'D'): raise LineUnsupportedValueError("polling_pcl: unsupported discipline.", error_id='LINE:unsupported:SchedStrategy_POLLING') if c == 'L' and K != 1: raise LineUnsupportedValueError( "polling_pcl: no pseudo-conservation law of this form is known " "for limited service with K>1.", error_id='LINE:unsupported:SchedStrategy_POLLING') return c if isinstance(disc, list): if len(disc) != n: raise LineUnsupportedValueError("polling_pcl: DISC must give one discipline per queue.", error_id='LINE:unsupported:SchedStrategy_POLLING') return ''.join(one(d) for d in disc) return one(disc) * n
[docs] def polling_pcl(arvMAPs, svcMAPs, switchMAPs, disc): """Pseudo-conservation law of a cyclic polling system with Poisson arrivals. Mirrors MATLAB api/polling/polling_pcl.m (Boxma and Groenendijk 1987; Takagi, ACM Computing Surveys 20(1), 1988, eq (10)). The law is exact for any mix of exhaustive, gated, 1-limited and decrementing queues: SUM_i w[i]*E[W_i] = rhs. Args: arvMAPs, svcMAPs, switchMAPs: as polling_qsys_exhaustive (MAPs or the numeric moment forms of _polling_moments). disc: a PollingType (or 'E','G','L','D'), a (PollingType, K) tuple with K=1 for limited service, or a list of these per queue. Returns: (w, rhs, pcl): the weights, the right-hand side and rhs/sum(w). """ arvMAPs = [_numeric_form(x) for x in arvMAPs] svcMAPs = [_numeric_form(x) for x in svcMAPs] switchMAPs = [_numeric_form(x) for x in switchMAPs] lam, b, b2, r1, delta2 = _polling_moments(arvMAPs, svcMAPs, switchMAPs) code = _pcl_codes(disc, len(lam)) w, rhs = _pcl_terms(lam, b, b2, r1, delta2, code) return w, rhs, rhs / float(np.sum(w))