{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Queuing design\n",
    "\n",
    "In this example, we consider the design of an $M/M/N$ queuing system, and we study the sensitivity of the design with respect to various parameters, such as the maximum total delay and total service rate.\n",
    "\n",
    "This example was described in the paper [Differentiating through Log-Log Convex Programs](http://web.stanford.edu/~boyd/papers/pdf/diff_llcvx.pdf)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We consider the optimization of a (Markovian) queuing system, with $N$\n",
    "queues. A queuing system is a collection of queues, in which queued items\n",
    "wait to be served; the queued items might be threads in an operating system,\n",
    "or packets in an input or output buffer of a networking system. A natural goal\n",
    "to minimize the service load of the system, given constraints on various\n",
    "properties of the queuing system, such as limits on the maximum delay or latency.\n",
    "In this example, we formulate this design problem as a log-log convex program (LLCP), and compute the\n",
    "sensitivity of the design variables with respect to the parameters.\n",
    "The queuing system under consideration here is known as an $M/M/N$ queue.\n",
    "\n",
    "We assume that items arriving at the $i$th queue are generated by a\n",
    "Poisson process with rate $\\lambda_i$, and that the service times for the $i$th\n",
    "queue follow an exponential distribution with parameter $\\mu_i$, for $i=1,\n",
    "\\ldots, N$. The \\emph{service load} of the queuing system is a\n",
    "function $\\ell : \\mathbf{R}^{N}_{++} \\times \\mathbf{R}^{N}_{++} \\to \\mathbf{R}^{N}_{++}$\n",
    "of the arrival rate vector $\\lambda$ and the service rate vector\n",
    "$\\mu$, with components\n",
    "\n",
    "$$\n",
    "\\ell_i(\\lambda, \\mu) = \\frac{\\mu_i}{\\lambda_i}, \\quad i=1, \\ldots, N.\n",
    "$$\n",
    "\n",
    "(This is the reciprocal of the traffic load, which is usually denoted by $\\rho$.)\n",
    "Similarly, the queue occupancy, the average delay, and the total delay\n",
    "of the system are (respectively) functions $q$, $w$, and $d$ of $\\lambda$\n",
    "and $\\mu$, with components\n",
    "\n",
    "$$\n",
    "q_i(\\lambda, \\mu) =\n",
    "\\frac{\\ell_i(\\lambda, \\mu)^{-2}}{1 - \\ell_i(\\lambda, \\mu)^{-1}}, \\quad\n",
    "w_i(\\lambda, \\mu) = \\frac{q_i(\\lambda, \\mu)}{\\lambda_i} + \\frac{1}{\\mu_i}, \\quad\n",
    "d_i(\\lambda, \\mu) = \\frac{1}{\\mu_i - \\lambda_i}\n",
    "$$\n",
    "\n",
    "These functions have domain $\\{(\\lambda, \\mu) \\in \\mathbf{R}^{N}_{++} \\times\n",
    "\\mathbf{R}^{N}_{++} \\mid \\lambda < \\mu \\}$, where the inequality\n",
    "is meant elementwise. The queuing system has limits on the queue occupancy,\n",
    "average queuing delay, and total delay, which must satisfy\n",
    "\n",
    "$$\n",
    "q(\\lambda, \\mu) \\leq q_{\\max}, \\quad w(\\lambda, \\mu) \\leq w_{\\max}, \\quad d(\\lambda, \\mu) \\leq d_{\\max},\n",
    "$$\n",
    "\n",
    "where $q_{\\max}$, $w_{\\max}$, and $d_{\\max} \\in \\mathbf{R}^{N}_{++}$ are\n",
    "parameters and the inequalities are meant elementwise. Additionally, the arrival\n",
    "rate vector $\\lambda$ must be at least $\\lambda_{\\mathrm{min}} \\in \\mathbf{R}^{N}_{++}$, and the sum of\n",
    "the service rates must be no greater than $\\mu_{\\max} \\in \\mathbf{R}_{++}$.\n",
    "\n",
    "Our design problem is to choose the arrival rates and service times to\n",
    "minimize a weighted sum of the service loads, $\\gamma^T \\ell(\\lambda, \\mu)$,\n",
    "where $\\gamma \\in \\mathbf{R}^{N}_{++}$ is the weight vector, while satisfying the\n",
    "constraints. The problem is\n",
    "\n",
    "$$\n",
    "\\begin{array}{ll}\n",
    "\\mbox{minimize} & \\gamma^T \\ell(\\lambda, \\mu) \\\\\n",
    "\\mbox{subject to}\n",
    "& q(\\lambda, \\mu) \\leq q_{\\max} \\\\\n",
    "& w(\\lambda, \\mu) \\leq w_{\\max} \\\\\n",
    "& d(\\lambda, \\mu) \\leq d_{\\max} \\\\\n",
    "& \\lambda \\geq \\lambda_{\\mathrm{min}}, \\quad\n",
    "\\sum_{i=1}^{N} \\mu_i \\leq \\mu_{\\max}.\n",
    "\\end{array}\n",
    "$$\n",
    "\n",
    "Here, $\\lambda, \\mu \\in \\mathbf{R}^{N}_{++}$ are the\n",
    "variables and $\\gamma, q_{\\max}, w_{\\max}, d_{\\max},\n",
    "\\lambda_{\\mathrm{min}} \\in \\mathbf{R}^{N}_{++}$ and $\\mu_{\\max} \\in \\mathbf{R}_{++}$\n",
    "are the parameters. This problem is an LLCP.\n",
    "The objective function is a posynomial, as is the constraint function $w$. The functions\n",
    "$d$ and $q$ are not posynomials, but they are log-log convex; log-log convexity\n",
    "of $d$ follows from the composition rule, since the\n",
    "function $(x, y) \\mapsto y - x$ is log-log concave (for $0 < x < y$), and the ratio $(x, y) \\mapsto\n",
    "x/y$ is log-log affine and decreasing in $y$. By a similar argument,\n",
    "$q$ is also log-log convex."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.457106781186705"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cvxpy as cp\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "\n",
    "mu = cp.Variable(pos=True, shape=(2,), name='mu')\n",
    "lam = cp.Variable(pos=True, shape=(2,), name='lambda')\n",
    "ell = cp.Variable(pos=True, shape=(2,), name='ell')\n",
    "\n",
    "w_max = cp.Parameter(pos=True, shape=(2,), value=np.array([2.5, 3.0]), name='w_max')\n",
    "d_max = cp.Parameter(pos=True, shape=(2,), value=np.array([2., 2.]), name='d_max')\n",
    "q_max = cp.Parameter(pos=True, shape=(2,), value=np.array([4., 5.0]), name='q_max')\n",
    "lam_min = cp.Parameter(pos=True, shape=(2,), value=np.array([0.5, 0.8]), name='lambda_min')\n",
    "mu_max = cp.Parameter(pos=True, value=3.0, name='mu_max')\n",
    "gamma = cp.Parameter(pos=True, shape=(2,), value=np.array([1.0, 2.0]), name='gamma')\n",
    "                     \n",
    "lq = (ell)**(-2)/cp.one_minus_pos(ell**(-1))\n",
    "q = lq\n",
    "w = lq/lam + 1/mu\n",
    "d = 1/cp.diff_pos(mu, lam)                    \n",
    "\n",
    "constraints = [\n",
    "    w <= w_max,\n",
    "    d <= d_max,\n",
    "    q <= q_max,\n",
    "    lam >= lam_min,\n",
    "    cp.sum(mu) <= mu_max,\n",
    "    ell == mu/lam,\n",
    "]\n",
    "\n",
    "objective_fn = gamma.T @ ell\n",
    "\n",
    "problem = cp.Problem(cp.Minimize(objective_fn), constraints)\n",
    "problem.solve(requires_grad=True, gp=True, eps=1e-14, max_iters=10000, mode='dense')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The solution is printed below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mu  [1.32842713 1.67157287]\n",
      "lam  [0.82842712 1.17157287]\n",
      "ell  [1.60355339 1.4267767 ]\n"
     ]
    }
   ],
   "source": [
    "print('mu ', mu.value)\n",
    "print('lam ', lam.value)\n",
    "print('ell ', ell.value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sensitvities\n",
    "\n",
    "We compute the derivative of each variable with respect the parameters. One takeaway is that the solution is highly sensitive to the values of $d_{\\max}$ and $\\mu_{\\max}$, and that increasing these parameters would decrease the service loads, especially on the first queue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Variable  lambda\n",
      "Gradient with respect to first component\n",
      "gamma: 0.213, -0.107\n",
      "w_max: 5.43e-12, 5.64e-12\n",
      "d_max: -0.411, -0.113\n",
      "q_max: 5.99e-12, 4.77e-12\n",
      "lambda_min: -1.56e-11, -7.35e-12\n",
      "mu_max: 0.927\n",
      "Gradient with respect to second component\n",
      "gamma: -0.458, 0.229\n",
      "w_max: 2.08e-11, 2.16e-11\n",
      "d_max: -0.105, -0.466\n",
      "q_max: 2.29e-11, 1.83e-11\n",
      "lambda_min: -5.97e-11, -2.82e-11\n",
      "mu_max: 1.01\n",
      "\n",
      "Variable  mu\n",
      "Gradient with respect to first component\n",
      "gamma: 0.213, -0.107\n",
      "w_max: 1.55e-11, 1.6e-11\n",
      "d_max: -0.661, -0.113\n",
      "q_max: 1.7e-11, 1.36e-11\n",
      "lambda_min: -4.43e-11, -2.09e-11\n",
      "mu_max: -0.0727\n",
      "Gradient with respect to second component\n",
      "gamma: -0.458, 0.229\n",
      "w_max: 2.3e-11, 2.39e-11\n",
      "d_max: -0.105, -0.716\n",
      "q_max: 2.53e-11, 2.02e-11\n",
      "lambda_min: -6.59e-11, -3.11e-11\n",
      "mu_max: 0.00996\n",
      "\n",
      "Variable  ell\n",
      "Gradient with respect to first component\n",
      "gamma: -0.245, 0.122\n",
      "w_max: 2e-11, 2.08e-11\n",
      "d_max: -0.282, -0.22\n",
      "q_max: 2.21e-11, 1.76e-11\n",
      "lambda_min: -5.74e-11, -2.71e-11\n",
      "mu_max: -0.334\n",
      "Gradient with respect to second component\n",
      "gamma: 0.122, -0.0611\n",
      "w_max: -1.24e-13, -1.29e-13\n",
      "d_max: -0.101, -0.195\n",
      "q_max: -1.37e-13, -1.09e-13\n",
      "lambda_min: 3.58e-13, 1.66e-13\n",
      "mu_max: -0.197\n",
      "\n"
     ]
    }
   ],
   "source": [
    "problem.solve(requires_grad=True, gp=True, eps=1e-14, max_iters=10000, mode='dense')\n",
    "\n",
    "for var in [lam, mu, ell]:\n",
    "    print('Variable ', var.name())\n",
    "    print('Gradient with respect to first component')\n",
    "    var.gradient = np.array([1., 0.])\n",
    "    problem.backward()\n",
    "    for param in problem.parameters():\n",
    "        if np.prod(param.shape) == 2:\n",
    "            print('{0}: {1:.3g}, {2:.3g}'.format(param.name(), param.gradient[0], param.gradient[1]))\n",
    "        else:\n",
    "            print('{0}: {1:.3g}'.format(param.name(), param.gradient))\n",
    "\n",
    "    print('Gradient with respect to second component')\n",
    "    var.gradient = np.array([0., 1.])\n",
    "    problem.backward()\n",
    "    for param in problem.parameters():\n",
    "        if np.prod(param.shape) == 2:\n",
    "            print('{0}: {1:.3g}, {2:.3g}'.format(param.name(), param.gradient[0], param.gradient[1]))\n",
    "        else:\n",
    "            print('{0}: {1:.3g}'.format(param.name(), param.gradient))\n",
    "    \n",
    "    var.gradient = np.zeros(2)\n",
    "    print('')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Perturbation analysis\n",
    "\n",
    "Next, we perturb each parameter by a small amount, and compare the prediction of a first-order approximation to the solution of the perturbed problem to the true solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lam predicted (percent change):  [2.32203282 1.77228841]\n",
      "mu predicted (percent change):  [1.07166961 0.94304296]\n",
      "lam actual (percent change):  [1.99504983 1.99504965]\n",
      "mu actual (percent change):  [0.87148458 1.10213353]\n"
     ]
    }
   ],
   "source": [
    "problem.solve(requires_grad=True, gp=True, eps=1e-14, max_iters=10000, mode='dense')\n",
    "\n",
    "mu_value = mu.value\n",
    "lam_value = lam.value\n",
    "\n",
    "delta = 0.01\n",
    "for param in problem.parameters():\n",
    "    param.delta = param.value * delta\n",
    "    \n",
    "problem.derivative()\n",
    "\n",
    "lam_pred = (lam.delta / lam_value) * 100\n",
    "mu_pred = (mu.delta / mu_value) * 100\n",
    "\n",
    "print('lam predicted (percent change): ', lam_pred)\n",
    "print('mu predicted (percent change): ', mu_pred)\n",
    "\n",
    "\n",
    "for param in problem.parameters():\n",
    "    param._old_value = param.value\n",
    "    param.value += param.delta\n",
    "problem.solve(cp.SCS, gp=True, eps=1e-14, max_iters=10000)\n",
    "\n",
    "lam_actual = ((lam.value - lam_value) / lam_value) * 100\n",
    "mu_actual = ((mu.value - mu_value) / mu_value) * 100\n",
    "    \n",
    "print('lam actual (percent change): ', lam_actual)\n",
    "print('mu actual (percent change): ', mu_actual)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
