{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "NzOv5nch3OqM" }, "source": [ "### **ORIE 3120 Recitation 11**" ] }, { "cell_type": "markdown", "metadata": { "id": "0uipijjU6mc9" }, "source": [ "## **1. Introduction**" ] }, { "cell_type": "markdown", "metadata": { "id": "iEP16BeO3OfZ" }, "source": [ "**Due on Friday, April 22**\n", "\n", "In this recitation we will learn how to employ the newsvendor problem to solve a scheduling problem. More specifically, we want to find the optimal number of nurses to be scheduled to work on the quarantine & isolation team at Cornell Health to handle positive COVID tests.\n", "\n", "Whenever a student tests positive, this team of nurses calls that student to check on their symptoms and to move them to a room at a hotel. The nursing team also calls students identified as close contacts of the positive student, and who may have already been infected, to move them into quarantine at a hotel. This is done to protect against the possibility that others would be infected by coming into contact with someone who is infectious. In many cases this is straightforward but it sometimes requires a substantial amount of work: the person being contacted might have a medical situation that requires extra attention (either from COVID or another condition); might not answer their phone (requiring repeated calls); might be belligerent or misrepresent the truth (requiring a longer conversation and sometimes the use of additional resources); or might simply have a great number of questions.\n", "\n", "This is a newsvendor problem because demand is stochastic and there is a cost both for scheduling too few nurses, and for scheduling too many. If we schedule too many nurses, we create a burden for them and risk burning out the nursing team. If we schedule too few, we can ask unscheduled nurses to come on and work at the last minute, but this forces them to drop their personal life and start working (creating a burden and risking burnout). Also, scheduling too few nurses creates a risk that we might not be able to contact and move to quarantine / isolation all of the students who are potentially infectious, risking the creation of new COVID cases.\n", "\n", "We focus on the arrival period for the Spring 2021 semester. During this period, students arriving from elsewhere were testing positive due to infections acquired at home. The rapid increase in arriving students and the changing nature of nationwide and international prevalence relative to the Fall 2020 semester made it difficult to plan based on past experience. This made mathematical modeling extremely useful. Indeed, code close to this recitation was actually used to make staffing decisions at Cornell Health over this period." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NpM9uWJP3Ykp" }, "outputs": [], "source": [ "# Importing basic libraries\n", "import numpy as np\n", "import pandas as pd\n", "import numpy.random as rand\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "%matplotlib inline\n", "import math\n", "import time\n", "from IPython import display\n", "\n", "# Setting the default parameters for the plots produced by matplotlib\n", "# Sets figure size. Width, height in inches.\n", "plt.rcParams[\"figure.figsize\"] = (10,10)\n", "# Sets label font sizes\n", "plt.rcParams['axes.labelsize'] = 14\n", "plt.rcParams['xtick.labelsize'] = 12\n", "plt.rcParams['ytick.labelsize'] = 12" ] }, { "cell_type": "markdown", "metadata": { "id": "0MP4NOMo6sez" }, "source": [ "## **2. Planning for a Single Day**" ] }, { "cell_type": "markdown", "metadata": { "id": "k8OBQdjo7YPe" }, "source": [ "We will start by creating a model that plans for a single day, finding the optimal number of nurses to schedule for that day." ] }, { "cell_type": "markdown", "metadata": { "id": "cZ6dZ2YLAT1F" }, "source": [ "First, we will model the probability of testing positive for an arriving student by specifying some constants. \n", "\n", "We model students as arriving from one of the following location categories - 'New York State', 'Middle States', 'New England', 'Midwest', 'South', 'Southwest', 'West', 'Territories', 'USA, unknown', and 'International'. \n", "\n", "If we know the distribution of the arriving Cornell student population over these location categories, and the COVID prevalence at each of these locations, we can estimate the probability that an arriving student will person testing postive if they arrive from 'X' location.\n", "\n", "We can get the data we need from\n", "https://www.cornell.edu/about/facts.cfm" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 204 }, "id": "N6cemiLRAFzH", "outputId": "ad4a32d5-2922-4ae1-bd95-bff92b1a079d" }, "outputs": [], "source": [ "# Data from website\n", "locations = ['New York State','Middle States','New England','Midwest','South',\n", " 'Southwest','West','Territories','USA, unknown', 'International'] # Location categories\n", "pop_percent = [27,12,7,6,8,3,11,2,2,22] # Probability distribution of the origin locations for incoming Cornell students \n", "covid_prevalence = [1.3,1.4,1.6,1.9,2.0,1.7,1.8,2.4,2.5,3.1] # the probability that a person coming from each origin has COVID\n", "# Both pop_percent and covid_percents are expressed as percentages between 0 and 100.\n", "\n", "# Create a dataframe with the above information\n", "data = pd.DataFrame(list(zip(locations, pop_percent, covid_prevalence)), columns=['location','pop_percent','covid_prevalence'])\n", "\n", "data.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "pkbIwPpvCFlZ" }, "source": [ "**Question 1:** Write code that calculates the probability that an arriving student tests positive. This is $$\\sum_i P(\\text{student origin is $i$}) P(\\text{student is positive} | \\text{origin is $i$})$$\n", "Store this in a variable `prevalence` as a probability between 0 and 1.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "5x-I9hrWS99x" }, "source": [ "We will now run a simulation to generate many scenarios. \n", "\n", "Each scenario will include the number of positive students arriving on the day we are planning for, which is a binomial(p,n) random variable where p is the prevalence you calculated in question 1 and n is the number of students that arrive on that day. We set the number of arriving students to 1000.\n", "\n", "It will then calculate the number of minutes of work required to handle those positive students, assuming that each positive case requires 30 minutes, each of their contacts requires 20 minutes, and each positive case has 4 contacts. \n", "\n", "It then calculates the number of nurses needed to do this work, assuming that each nurse works an 8 hour shift." ] }, { "cell_type": "markdown", "metadata": { "id": "gWg_WodCFwTY" }, "source": [ "**Question 2:** Fill in the two missing lines in the code below" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 130 }, "id": "rfjUHaHtdFHM", "outputId": "ccd68e0c-77a8-4cf0-875a-1c479c8e9a82" }, "outputs": [], "source": [ "# Defining constants\n", "num_arrivals = 1000 # Number of arriving students\n", "M = 1000 # Number of simulation replications\n", "\n", "nurses_needed = []\n", "num_pos = [0]*M\n", "work = [0]*M\n", "\n", "# Run simulation\n", "for m in range(M):\n", " num_pos[m] = # Simulate a binomial(N, prevalence) random variable \n", " work[m] = # 30 min per positive, 20 min per contact, 4 contacts, work defined in terms of minutes \n", " nurses_needed.append(int(work[m] / (8*60))) # nurse works 8h (8 x 60 minutes) shift\n", "\n", "simulation_df = pd.DataFrame(nurses_needed, columns = ['nurses_needed'])\n", "simulation_df.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "hpMXXNEoAk8H" }, "source": [ "To optimize for the number of nurses we bring in, we will write a function that calculates the number of extra nurses required given that `N` nurses are currently working using our simulated data.\n", "\n", "As discussed at the beginning of this recitation, there are two bad things that can happen: \n", "* the number of nurses scheduled on the day we are planning for could be *strictly more* than the number needed to do the work necessary on this day. In this case, the difference between the number scheduled and the number needed is called *overage*\n", "* the number of nurses scheduled on the day we are planning for could be *strictly less* than the number needed to do the work necessary on this day. In this case, the difference between the number needed and the number scheduled is called *underage*.\n", "\n", "In particular, if the number of nurses scheduled is N and the number of nurses needed is D, then:\n", "* Overage = max(0,N-D)\n", "* Underage = max(0,D-N)\n", "\n", "We estimate the expected overage and expected underage associated with a particular number of scheduled nurses, we calculate the overage and underage on each scenario and return the average over all scenarios.\n", "\n", "**Question 3:** Fill in the two lines below to define a function that calculates the overage and underage from `sim_df`.\n", "\n", "Hint: One way to do this very quickly is to use the `clip` function with the `lower` keyword. `df['x'].clip(lower=0)` returns the value of max(x,0) for each entry in `df['x']`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8eHb2CkPIZLK" }, "outputs": [], "source": [ "def eval_N(nurses_needed, nurses_scheduled):\n", " overage = # FILL IN\n", " underage = # FILL IN\n", " return underage, overage\n", "\n", "eval_N(sim_df['nurses_needed'],1)" ] }, { "cell_type": "markdown", "metadata": { "id": "mThhbEkU8XmI" }, "source": [ "**Question 4**: Using `eval_N`, plot the underage and overage vs. the number of nurses scheduled. Do this for `nurses_scheduled` ranging from 0 to 9 inclusive. You should see that the underage is high when not many nurses are scheduled (our planned resourcing is *under* demand) and overage is high when many nurses are scheduled (our planned resourcing is *over* demand)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nRTI7qRvCkQW" }, "outputs": [], "source": [ "# Your code below" ] }, { "cell_type": "markdown", "metadata": { "id": "UR7a5CWaOyvr" }, "source": [ "Now, we want to define a function `optimize(df, alpha)`. It should return:\n", "* the optimal number of nurses to schedule such that we minimize the total cost (alpha*underage + overage). \n", "* the underage and overage at this optimal number of nurses to schedule\n", "\n", "We will assume that we can schedule N = 0 to 9 (inclusive) nurses. For each N find the cost and return the N with least associated cost. \n", "\n", "**Question 5**: A part of the function has been filled in for you. Please complete the function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "c0v2hA0TOzSK" }, "outputs": [], "source": [ "def optimize(nurses_needed, alpha):\n", " cost = [0]*10\n", " best_cost = np.inf\n", " opt_N = -1\n", " opt_underage = -1\n", " opt_overage = -1\n", " for N in range(10):\n", " # Your code here (fill in the for-loop)\n", "\n", " return opt_N, opt_underage, opt_overage" ] }, { "cell_type": "markdown", "metadata": { "id": "vhXBtWHcNHQC" }, "source": [ "**Question 6**: Test your function by using it to find the optimal N, underage and overage at these values:\n", "* alpha = 0 (you should see that the optimal overage is 0 and the optimal N is 0)\n", "* alpha = 1000 (you should see that the optimal underage is close to 0 and the optimal N is big)\n", "* alpha = 1 (you should see the optimal underage and overage are similar to each other, and the optimal N is roughly in the middle between 0 and 10)" ] }, { "cell_type": "markdown", "metadata": { "id": "3yVi0rKzMTuv" }, "source": [ "**Creating a Pareto Frontier**\n", "\n", "Unfortunately, it isn't easy for a human decision-maker to tell you their objective function. Instead, what we can do is to plot things that must be traded off in an optimal solution and ask them to choose the trade-off they like the best. This is called a \"Pareto Frontier\".\n", "\n", "We can do this here by solving the optimization problem for many different values of alpha, calculating the underage and overage for each one, and then plotting underage vs. overage.\n", "\n", "The nurse manager or medical director would then be able to select a point on this curve that they think will be best. We can then look up which value of alpha generated this point and what the optimal N was.\n", "\n", "**Question 7:** \n", "Write code to create a Pareto frontier, " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "alpha = np.arange(0,2.5,.05)\n", "overage = [0] * len(alpha)\n", "underage = [0] * len(alpha)\n", "opt_N = [0] * len(alpha)\n", "for i in range(len(alpha)):\n", " # FILL IN YOUR CODE HERE\n", "\n", "plt.plot(underage,overage,'.-')\n", "plt.title('Plan for Monday Feb 4')\n", "plt.xlabel('Underage Nurses')\n", "plt.ylabel('Overage Nurses')" ] }, { "cell_type": "markdown", "metadata": { "id": "3tU_xPYfiVEC" }, "source": [ "When we show this plot to management, they say that they like the point that has underage closest to 0.4 (roughly speaking this means that the probability is 40% that we'll need to call in an extra nurse).\n", "\n", "**Question 8:** \n", "What is the number of nurses that we should schedule to achieve this tradeoff between overage and underage? What is the value of alpha that gave us this optimal number of nurses?" ] }, { "cell_type": "markdown", "metadata": { "id": "-fJ_bNLkOrMC" }, "source": [ "## **3. Planning for Multiple Days**" ] }, { "cell_type": "markdown", "metadata": { "id": "7EpsT1qI3S3m" }, "source": [ "### Setup\n", "\n", "Our current model only simulates a single day. However, we would like to have an optimal schedule for the number of nurses to employ for an entire period, say 3 weeks. We could do this by making 21 plots using the code above, one for each day, using the number of students scheduled to arrive for that day. We could then show each of those 21 plots to management and have them pick out a point on each plot. This would be a pain, however. It is better to show them a single plot for the entire 3-week period and have them select a point.\n", "\n", "In addition, we would like to introduce the possibility that a student does not test positive immediately upon arriving and thus contacts multiple students during the time he/she goes undetected. For simplicity, we do not assume the contacted students spread the virus to other contacts.\n", "\n", "For example, a student arriving on day 0 may not test positive until day 4, and he/she may contact 6 students. We will implement this improved model below. \n", "\n", "Before we do so, note that our objective is essentially still the same as above: for a particular $\\alpha$ optimally choose the number of nurses to schedule to minimize the expected total cost. However, our choice of nurses to schedule is no longer a scalar, since we are considering *many* days as opposed to a single day. Rather, it is a vector (say, $\\vec{N}$) whose length is the number of days in the period we are considering, and whose $j$th entry is our choice of the number of nurses to employ on day $j$. " ] }, { "cell_type": "markdown", "metadata": { "id": "zLmPt5Pc3ats" }, "source": [ "---\n", "*For the mathematically inclined, our problem can be restated as the following optimization problem. (You may skip reading this cell, but it may help give you a better understanding of the problem at hand.)*\n", "\n", "Let $(N_1, ..., N_D) = \\vec{N}$ be a vector giving the number of nurses that will work on each day ($1$ through $D$), then, for a particular value of $\\alpha$, our objective function is:\n", "\n", "Objective$(\\vec{N})$ = ExpectedTotalOverage($\\vec{N}$) + $\\alpha \\cdot$ ExpectedTotalUnderage($\\vec{N}$) \n", "\n", "= $\\sum_{d=1}^{D}$ $E$ (Overage for day $d$ + $\\alpha \\cdot$ Underage for day $d$ | We use $N_d$ nurses on day $d$) \n", "\n", "$\\approx$ $\\sum_{d=1}^{D}$ $\\frac{1}{M}$ $\\sum_{i=1}^{M}$ (Overage for day $d$ $+ \\alpha \\cdot$ Underage for day $d$ | We use $N_d$ nurses on day $d$ and the random outcome for simulation $i$ is $(amount\\_of\\_work)_i \\in \\mathbb{R}_{\\geq 0}$) where $M$ is the number of simulations.\n", "\n", "Let $N^*(\\alpha)$ be the optimal choice of $N_1,...,N_D$ for a particular $\\alpha$ (i.e. the $\\vec{N}$ that minimizes the Objective function), then we would like to ultimately plot the _Pareto Frontier_ : ExpectedTotalOverage($N^*(\\alpha)$) vs. ExpectedTotalUnderage($N^*(\\alpha)$).\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "id": "bLCkd0XN1hP5" }, "source": [ "# Simulation\n", "\n", "Here we'll simulate scenarios, where each scenarios consists of the amount of work that needs to be done on each day during the first 3 weeks of the semester" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "htaJBw313Buo" }, "outputs": [], "source": [ "num_days = 21\n", "num_scenarios = 20\n", "\n", "# This is the number of people who arrive on each day.\n", "# It was generated using num_arrivals = np.ceil(2000*rand.uniform(size=num_days)) \n", "num_arrivals = [1076., 1752., 1783., 1326., 1385., 1454., 1230., 689., 1190.,\n", " 1853., 1716., 405., 70., 1097., 1504., 634., 1407., 1222.,\n", " 1140., 404., 1703.]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9y3Sz_SIrCwV" }, "outputs": [], "source": [ "# Create a dataframe containing all 0's where each row will be a scenario\n", "# and each column will be a simulated day. Once we run the code below, the\n", "# values in the dataframe will be the number of nurses needed on each day in \n", "# each scenario\n", "df_sim = pd.DataFrame(0, index=range(num_scenarios), columns=range(num_days))\n", "\n", "for i in range(num_scenarios):\n", " for d in range(num_days): # Iterate over days in our simulation\n", " # Simulate the students who arrive on this day\n", " infected_no = rand.binomial(num_arrivals[d],prevalence)\n", " for j in range(infected_no):\n", " days_infectious = rand.geometric(0.3)\n", " day_tested_positive = d + days_infectious\n", " if day_tested_positive < num_days:\n", " contacts = 4\n", " df_sim.loc[i,day_tested_positive] += (30 + 20 * contacts)/(8*60)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 689 }, "id": "qPArjKKdujp1", "outputId": "fee7e519-9e07-4bff-d481-bf8fbf926590" }, "outputs": [], "source": [ "df_sim" ] }, { "cell_type": "markdown", "metadata": { "id": "en_MWjlY10wF" }, "source": [ "**Question 9**: Change the above code so that the number of contacts depends on the number of days the person is infectious. Let the number of contacts be 1.5 times the number of days infectious. This models the fact that a person who has been circulating in the campus population is going to have more local contacts." ] }, { "cell_type": "markdown", "metadata": { "id": "MOGoC7KY3pWX" }, "source": [ "**Question 10:** Plot the average amount of work per day vs. day, averaging across all of the scenarios. You will probably see that the amount of work is larger for later days, even though the distribution over the number of arriving students and the prevalence was the same on every day. Why is that?" ] }, { "cell_type": "markdown", "metadata": { "id": "956j8A1G2Vrz" }, "source": [ "# Optimization\n", "\n", "For each value of alpha, we will now find the optimal schedule of nurses. This is just like we did above, except now we will take multiple days into account. Fortunately, the optimal schedule over multiple days for a given alpha can be optimized separately for each day.\n", "\n", "To optimize for a given value of alpha, we need to use the `optimize` function we wrote above. We use this to figure out the optimal number of nurses to schedule on that day, treating that day separately from all other days. This also tells us the optimal underage and overage on that day.\n", "\n", "We can then add up the overage and underage costs across all days to get the total underage and overage.\n", "\n", "**Question 11** Fill in the missing line of code below using your `optimize` function to complete this." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GxynySFYwcne" }, "outputs": [], "source": [ "best = pd.DataFrame()\n", "best['alpha'] = np.arange(0,5,.25)\n", "best['underage'] = 0\n", "best['overage'] = 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 130 }, "id": "y4_UU6ASUe0H", "outputId": "21efa492-3c34-4b12-aec3-341afb8fb3ea" }, "outputs": [], "source": [ "for index, row in best.iterrows():\n", " for d in df_sim.columns:\n", " opt_N, underage, overage = # FILL IN\n", " # These are the total values, across all days\n", " best.loc[index,'underage'] += underage\n", " best.loc[index,'overage'] += overage" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 669 }, "id": "TQ3CSXtY0uir", "outputId": "efcb1d9d-7c91-4ff8-c4a4-fa1479303b0a" }, "outputs": [], "source": [ "best" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 303 }, "id": "8toVf2xA_TCv", "outputId": "cd1801c9-9d35-4895-c69b-13a28974391a" }, "outputs": [], "source": [ "plt.plot(best['underage'],best['overage'],'.-')\n", "plt.xlabel('Underage')\n", "plt.ylabel('Overage')" ] }, { "cell_type": "markdown", "metadata": { "id": "LKZqltf5Y9cq" }, "source": [ "**Question 12**\n", "Suppose that leadership says that they prefer the solution whose total underage over the 21 day period is closest to 10. What value (or values) of alpha that you searched does this correspond to? How many nurses are scheduled on each day under the optimal schedule for this choice for alpha? (If multiple values of alpha produce underage costs that are closes to 10, pick one.)" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "ORIE3120 SP21 Recitation 11.ipynb", "provenance": [], "toc_visible": true }, "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": 1 }