1. Introduction In this recitation we will learn how to employ the newsvendor problem to…
- User
- Introduction 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. 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. 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. 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.
Importing basic libraries
import numpy as np import pandas as pd import numpy.random as rand import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline import math import time from IPython import display
Setting the default parameters for the plots produced by matplotlib
Sets figure size. Width, height in inches.
plt.rcParams["figure.figsize"] = (10,10)
Sets label font sizes
plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12
- Planning for a Single Day We will start by creating a model that plans for a single day, finding the optimal number of nurses to schedule for that day.
- Assistant
Calculation of the probability that an arriving student tests positive
prevalence = np.sum(np.array(data['pop_percent'])/100 * np.array(data['covid_prevalence'])/100)
print("The probability that an arriving student tests positive is", round(prevalence, 4))
- User
We will now run a simulation to generate many scenarios. 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. 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. It then calculates the number of nurses needed to do this work, assuming that each nurse works an 8 hour shift.
Question 2: Fill in the two missing lines in the code below
Defining constants
num_arrivals = 1000 # Number of arriving students M = 1000 # Number of simulation replications
nurses_needed = [] num_pos = [0]*M work = [0]*M
Run simulation
for m in range(M): num_pos[m] = # Simulate a binomial(N, prevalence) random variable
work[m] = # 30 min per positive, 20 min per contact, 4 contacts, work defined in terms of minutes nurses_needed.append(int(work[m] / (8*60))) # nurse works 8h (8 x 60 minutes) shiftsimulation_df = pd.DataFrame(nurses_needed, columns = ['nurses_needed']) simulation_df.head()
- Assistant
Defining constants
num_arrivals = 1000 # Number of arriving students M = 1000 # Number of simulation replications
nurses_needed = [] num_pos = [0]*M work = [0]*M
Run simulation
for m in range(M): num_pos[m] = np.random.binomial(num_arrivals, prevalence) # Simulate a binomial(N, prevalence) random variable
work[m] = 30 * num_pos[m] + 4 * 20 * num_pos[m] # 30 min per positive, 20 min per contact, 4 contacts nurses_needed.append(int(work[m] / (8*60))) # nurse works 8h (8 x 60 minutes) shiftsimulation_df = pd.DataFrame(nurses_needed, columns = ['nurses_needed']) simulation_df.head()
- User
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. As discussed at the beginning of this recitation, there are two bad things that can happen:
- 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
- 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. In particular, if the number of nurses scheduled is N and the number of nurses needed is D, then:
- Overage = max(0,N-D)
- Underage = max(0,D-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. Question 3: Fill in the two lines below to define a function that calculates the overage and underage from sim_df. 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'].
- Assistant
def eval_N(nurses_needed, nurses_scheduled): overage = (sim_df['nurses_needed'] - nurses_scheduled).clip(lower=0).mean() underage = (nurses_scheduled - sim_df['nurses_needed']).clip(lower=0).mean() return underage, overage
eval_N(simulation_df['nurses_needed'], 1)
- User
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).
- Assistant
Plotting underage and overage vs. number of nurses scheduled
underage_list = [] overage_list = []
for N in range(0, 10): underage, overage = eval_N(simulation_df['nurses_needed'], N) underage_list.append(underage) overage_list.append(overage)
plt.plot(range(0,10), underage_list, label='Underage') plt.plot(range(0,10), overage_list, label='Overage') plt.xlabel('Number of Nurses Scheduled') plt.ylabel('Average Number of Nurses Wasted') plt.legend()
- User
Now, we want to define a function optimize(df, alpha). It should return:
- the optimal number of nurses to schedule such that we minimize the total cost (alpha*underage + overage).
- the underage and overage at this optimal number of nurses to schedule 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. Question 5: A part of the function has been filled in for you. Please complete the function.
def optimize(nurses_needed, alpha): cost = [0]*10 best_cost = np.inf opt_N = -1 opt_underage = -1 opt_overage = -1 for N in range(10): # Your code here (fill in the for-loop)
return opt_N, opt_underage, opt_overage
- Assistant
def optimize(nurses_needed, alpha): cost = [0]*10 best_cost = np.inf opt_N = -1 opt_underage = -1 opt_overage = -1 for N in range(10): underage, overage = eval_N(nurses_needed, N) cost[N] = alpha * underage + overage if cost[N] < best_cost: best_cost = cost[N] opt_N = N opt_underage = underage opt_overage = overage return opt_N, opt_underage, opt_overage
optimize(simulation_df['nurses_needed'], 1)
- User
Question 6: Test your function by using it to find the optimal N, underage and overage at these values: alpha = 0 (you should see that the optimal overage is 0 and the optimal N is 0) alpha = 1000 (you should see that the optimal underage is close to 0 and the optimal N is big) 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)
- Assistant
print("Results for alpha = 0:") opt_N, opt_underage, opt_overage = optimize(simulation_df['nurses_needed'], 0) print("Optimal Number of Nurses to Schedule: ", opt_N) print("Optimal Underage: ", opt_underage) print("Optimal Overage: ", opt_overage)
print("\nResults for alpha = 1000:") opt_N, opt_underage, opt_overage = optimize(simulation_df['nurses_needed'], 1000) print("Optimal Number of Nurses to Schedule: ", opt_N) print("Optimal Underage: ", opt_underage) print("Optimal Overage: ", opt_overage)
print("\nResults for alpha = 1:") opt_N, opt_underage, opt_overage = optimize(simulation_df['nurses_needed'], 1) print("Optimal Number of Nurses to Schedule: ", opt_N) print("Optimal Underage: ", opt_underage) print("Optimal Overage: ", opt_overage)
- User
Creating a Pareto Frontier 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". 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. 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. Question 7: Write code to create a Pareto frontier,
alpha = np.arange(0,2.5,.05) overage = [0] * len(alpha) underage = [0] * len(alpha) opt_N = [0] * len(alpha) for i in range(len(alpha)):
FILL IN YOUR CODE HERE
plt.plot(underage,overage,'.-') plt.title('Plan for Monday Feb 4') plt.xlabel('Underage Nurses') plt.ylabel('Overage Nurses')
- Assistant
alpha = np.arange(0, 2.5, 0.05) overage = [0] * len(alpha) underage = [0] * len(alpha) opt_N = [0] * len(alpha) for i in range(len(alpha)): opt_N[i], underage[i], overage[i] = optimize(simulation_df['nurses_needed'], alpha[i])
plt.plot(underage, overage, '.-') plt.title('Plan for Monday Feb 4') plt.xlabel('Underage Nurses') plt.ylabel('Overage Nurses')
- User
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). Question 8: 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?
- Assistant
To find the optimal number of nurses given the selected trade-off point, we can find the index of the element in
underagethat is closest to 0.4 and use this index to extract the corresponding number of nurses inopt_N.We can then look up the value of
alphathat gave us the optimal tradeoff point by finding the value inalphathat corresponds to the selected point.The optimal number of nurses we should schedule to achieve this tradeoff is:
opt_N = opt_N[np.abs(np.array(underage) - 0.4).argmin()]The value of alpha that gave us this optimal number of nurses can be found as follows:
alpha_opt = alpha[np.abs(np.array(underage) - 0.4).argmin()]We can print these values to get the complete answer.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.