{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# What's this notebook for?\n",
    "\n",
    "If you care about the compile time for your model, you should minimize the number of cvxpy Constraint and Variable objects necessary to specify your model. For example, if you needed to write the constraint \"Ax = b\", it is grealy preferred that you do this by \"A * x == b\", rather than \"a_i * x == b_i\" for every row a_i of A and every entry b_i of b.\n",
    "\n",
    "This notebook provides explicit demonstrations of how you can expect compile time for cvxpy to vary based on how you specify your model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "\n",
    "Throughout this notebook, we will consider the problem\n",
    "\n",
    "P(A,b,c) = min{ c.T * x  :  A x = b, 0 <= x <= 1}\n",
    "\n",
    "where A is an m-by-n matrix. Note that this is really the best-case scenario for cvxpy compile times: linear equality and inequality constraints require very few transformations before being handed to a low level solver. If you use more complex constraints (such as norm(x) <= d.T * x, or semidefinite constraints), you can expect the trends demonstrated in this notebook to become even more pronounced.\n",
    "\n",
    "At a high level, our tests are as follows: \n",
    "\tgenerate random problem data A, b, c of the appropriate sizes.\n",
    "\tconstruct a cvxpy Problem object \"prob\" representing P(A,b,c).\n",
    "\trecord the amount of time it takes for prob.solve(max_iters=1) to execute.\n",
    "\n",
    "Since we're only timing prob.solve(max_iters=1), it's clear that if *this* step runs too slow, the only option available to the user is to change how the problem is represented.\n",
    "\n",
    "The following code cell defines the helper functions we'll use in our tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cvxpy\n",
    "import scipy\n",
    "import time\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "\n",
    "def compile_time(prob, solver='ECOS'):\n",
    "    # Return the amount of time needed to call prob.solve(max_iters=1).\n",
    "    #\n",
    "    # Because we aren't giving the solver enough iterations to actually solve the problem,\n",
    "    # cvxpy will throw an error saying that the solver \"failed.\" We don't actually\n",
    "    # care that the solver only had one iteration to work with, we only care that the \n",
    "    # solver read the problem data.\n",
    "    start = time.time()\n",
    "    try:\n",
    "        prob.solve(solver=solver, max_iters=1)\n",
    "        end = time.time()\n",
    "    except cvxpy.SolverError:\n",
    "        end = time.time()\n",
    "    return end-start\n",
    "\n",
    "\n",
    "def gen_A_b_c(m, n):\n",
    "    # Generate data for a linear program which is guaranteed to be feasible.\n",
    "    A = scipy.sparse.rand(m, n, density=0.1).toarray()\n",
    "    x0 = np.random.rand(n, 1)\n",
    "    b = np.dot(A, x0)\n",
    "    c = np.random.randn(n, 1)\n",
    "    return A, b, c\n",
    "\n",
    "\n",
    "def scalarized_problem(A, b, c):\n",
    "    # Generate a cvxpy Problem object of the planned form, where \n",
    "    #   (1) upper and lower bounds are specified on each element of x individually, and\n",
    "    #   (2) equality constraints A x = b are specified one row at a time.\n",
    "    x = cvxpy.Variable(shape=(A.shape[1], 1))\n",
    "    constraints = list()\n",
    "    for i in range(x.size):\n",
    "        constraints.append(x[i] >= 0)\n",
    "        constraints.append(x[i] <= 1)\n",
    "    for i in range(A.shape[0]):\n",
    "        constraints.append(A[i, :] * x == b[i])\n",
    "    objective = cvxpy.Minimize(c.T * x)\n",
    "    prob = cvxpy.Problem(objective, constraints)\n",
    "    return prob\n",
    "\n",
    "\n",
    "def vectorized_problem(A, b, c):\n",
    "    # Generate a cvxpy Problem object of the planned form, where \n",
    "    #   (1) upper and lower bounds are specified on the entire vector \"x\" at once, and\n",
    "    #   (2) equality constraints A x = b are specified by a single cvxpy Constraint object.\n",
    "    x = cvxpy.Variable(shape=(A.shape[1], 1))\n",
    "    constraints = [0 <= x, x <= 1, A * x == b]\n",
    "    objective = cvxpy.Minimize(c.T * x)\n",
    "    prob = cvxpy.Problem(objective, constraints)\n",
    "    return prob"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test 1: Fix n and vary m.\n",
    "\n",
    "For our first set of tests, we'll fix n and vary m. This will allow us to see how cvxpy compile times vary when we linearly increase the size of the problems we're facing. It shouldn't take much more than 1 minute for the following cell to run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f17bfdca910>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 12180 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f17d751f8d0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ms1 = [250, 500, 1000, 1500, 2000]\n",
    "n = 250\n",
    "ts1 = list()\n",
    "tv1 = list()\n",
    "for m in ms1:\n",
    "    A, b, c = gen_A_b_c(m, n)\n",
    "    p = vectorized_problem(A, b, c)\n",
    "    tv1.append(compile_time(p))\n",
    "    p = scalarized_problem(A, b, c)\n",
    "    ts1.append(compile_time(p))\n",
    "\n",
    "plt.plot(ms1, ts1, 'r', label='scalarized')\n",
    "plt.plot(ms1, tv1, 'b', label='vectorized')\n",
    "plt.legend(loc='upper left')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From the plot above, we see that the time needed for a fully vectorized model to compile is virtually constant, even as the number of constraints varies over an order of magnitude. The scalarized model is subtantially slower than the vectorized model (even when m=250), and it exhibits a clear linear trend in the runtime complexity.\n",
    "\n",
    "It might be tempting to think that a linear trend in the number of constraints isn't a problem, and in some cases, it really isn't! However when practitioners solve larger and larger optimization problems, the number of variables tends to vary with the number of constraints. This coupling effectively means that when an engineer \"linearly\" increases the resolution of their optimization problem, cvxpy is actually handled problems that grow quadratically, if not worse. \n",
    "\n",
    "# Test 2: Vary n with m.\n",
    "\n",
    "In the following test, we compare cvxpy compile times for vectorized and scalarized models when n varies with m. To keep the runtime of this test to a reasonable level, we fix n = 2 * m. Note that even with this choice, it takes a few minutes for the following cell to run on our machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f17b00c3910>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 13808 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f17b608fc10>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ms2 = [250, 500, 1000, 1500, 2000]\n",
    "n_m_factor = 2\n",
    "ts2 = list()\n",
    "tv2 = list()\n",
    "for m in ms2:\n",
    "    A, b, c = gen_A_b_c(m, n=n_m_factor * m)\n",
    "    p = vectorized_problem(A, b, c)\n",
    "    tv2.append(compile_time(p, solver))\n",
    "    p = scalarized_problem(A, b, c)\n",
    "    ts2.append(compile_time(p, solver))\n",
    "    \n",
    "plt.plot(ms2, ts2, 'r', label='scalarized')\n",
    "plt.plot(ms2, tv2, 'b', label='vectorized')\n",
    "plt.legend(loc='upper left')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From the plot above we see that even the fully vectorized model exhibits a super-linear time complexity as the number of constraints increases. However, the extent to which this happens is tolerable for a variety of applications. The situation is different with the scalarized model; that model takes almost a full minute to handle the case with m=2000 and n=4000!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Closing Remarks\n",
    "\n",
    "We'd like to emphasize that these test cases are quite tame. The usefulness of cvxpy arises not from providing an interface for linear programming, but from providing an interface for a broad range of tractable convex programs. The work performed by cvxpy is to allow the user to provide natural input using these constructions, then transform that input for low level solvers with very rigid input requirements. The more complex these transformations are, the more the user benefits from specifying vectorized models. \n",
    "\n",
    "In fact, this notebook was written after a user working with the exponential cone (via the function kl_div) found that a *more* vectorized version of their model compiled in less than one second, while a *less* vectorized version of the same model took over 20 minutes to compile."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
