The Nurse Assignment Problem¶
This tutorial includes everything you need to set up IBM Decision Optimization CPLEX Modeling for Python (DOcplex), build a Mathematical Programming model, and get its solution by solving the model on the cloud with IBM ILOG CPLEX Optimizer.
When you finish this tutorial, you’ll have a foundational knowledge of Prescriptive Analytics.
Table of contents:
- Describe the business problem
- How decision optimization can help
- Use decision optimization
Describe the business problem¶
This notebook describes how to use CPLEX Modeling for Python together with pandas to manage the assignment of nurses to shifts in a hospital.
Nurses must be assigned to hospital shifts in accordance with various skill and staffing constraints.
The goal of the model is to find an efficient balance between the different objectives:
- minimize the overall cost of the plan and
- assign shifts as fairly as possible.
How decision optimization can help¶
Prescriptive analytics (decision optimization) technology recommends actions that are based on desired outcomes. It takes into account specific scenarios, resources, and knowledge of past and current events. With this insight, your organization can make better decisions and have greater control of business outcomes.
Prescriptive analytics is the next step on the path to insight-based actions. It creates value through synergy with predictive analytics, which analyzes data to predict future outcomes.
- Prescriptive analytics takes that insight to the next level by suggesting the optimal way to handle that future situation. Organizations that can act fast in dynamic conditions and make superior decisions in uncertain environments gain a strong competitive advantage.
With prescriptive analytics, you can:
- Automate the complex decisions and trade-offs to better manage your limited resources.
- Take advantage of a future opportunity or mitigate a future risk.
- Proactively update recommendations based on changing events.
- Meet operational goals, increase customer loyalty, prevent threats and fraud, and optimize business processes.
Checking minimum requirements¶
This notebook uses some features of pandas that are available in version 0.17.1 or above.
Use decision optimization¶
Step 1: Import the library¶
Run the following code to import the Decision Optimization CPLEX Modeling library. The DOcplex library contains the two modeling packages, Mathematical Programming (docplex.mp) and Constraint Programming (docplex.cp).
Step 2: Model the data¶
The input data consists of several tables:
- The Departments table lists all departments in the scope of the assignment.
- The Skills table list all skills.
- The Shifts table lists all shifts to be staffed. A shift contains a department, a day in the week, plus the start and end times.
- The Nurses table lists all nurses, identified by their names.
- The NurseSkills table gives the skills of each nurse.
- The SkillRequirements table lists the minimum number of persons required for a given department and skill.
- The NurseVacations table lists days off for each nurse.
- The NurseAssociations table lists pairs of nurses who wish to work together.
- The NurseIncompatibilities table lists pairs of nurses who do not want to work together.
Loading data from Excel with pandas¶
We load the data from an Excel file using pandas. Each sheet is read into a separate pandas DataFrame.
#nurses = 32 #shifts = 41 #vacations = 59
In addition, we introduce some extra global data:
- The maximum work time for each nurse.
- The maximum and minimum number of shifts worked by a nurse in a week.
Shifts are stored in a separate DataFrame.
Step 3: Prepare the data¶
We need to precompute additional data for shifts. For each shift, we need the start time and end time expressed in hours, counting from the beginning of the week: Monday 8am is converted to 8, Tuesday 8am is converted to 24+8 = 32, and so on.
We start by adding an extra column
dow (day of week) which converts
the string “day” into an integer in 0..6 (Monday is 0, Sunday is 6).
Sub-step #2 : Compute the absolute start time of each shift.¶
Computing the start time in the week is easy: just add
start_time. The result is stored in a new column
Sub-Step #3 : Compute the absolute end time of each shift.¶
Computing the absolute end time is a little more complicated as certain shifts span across midnight. For example, Shift #3 starts on Monday at 18:00 and ends Tuesday at 2:00 AM. The absolute end time of Shift #3 is 26, not 2. The general rule for computing absolute end time is:
abs_end_time = end_time + 24 * dow + (start_time>= end_time ? 24 : 0)
Again, we use pandas to add a new calculated column
wend. This is
done by using the pandas
apply method with an anonymous
function over rows. The
raw=True parameter prevents the creation of
a pandas Series for each row, which improves the performance
significantly on large data sets.
Sub-step #4 : Compute the duration of each shift.¶
Computing the duration of each shift is now a straightforward difference
of columns. The result is stored in column
Sub-step #5 : Compute the minimum demand for each shift.¶
Minimum demand is the product of duration (in hours) by the minimum
required number of nurses. Thus, in number of nurse-hours, this demand
is stored in another new column
Finally, we display the updated shifts DataFrame with all calculated columns.
Step 4: Set up the prescriptive model¶
* system is: Windows 64bit * Python version 3.7.3, located at: c:\local\python373\python.exe * docplex is present, version is (2, 11, 0) * pandas is present, version is 0.25.1
Create the DOcplex model¶
The model contains all the business constraints and defines the objective.
We now use CPLEX Modeling for Python to build a Mixed Integer Programming (MIP) model for this problem.
Define the decision variables¶
For each (nurse, shift) pair, we create one binary variable that is equal to 1 when the nurse is assigned to the shift.
We use the
binary_var_matrix method of class
Model, as each
binary variable is indexed by two objects: one nurse and one shift.
Express the business constraints¶
Some shifts overlap in time, and thus cannot be assigned to the same nurse. To check whether two shifts overlap in time, we start by ordering all shifts with respect to their wstart and duration properties. Then, for each shift, we iterate over the subsequent shifts in this ordered list to easily compute the subset of overlapping shifts.
We use pandas operations to implement this algorithm. But first, we organize all decision variables in a DataFrame.
For convenience, we also organize the decision variables in a pivot table with nurses as row index and shifts as columns. The pandas unstack operation does this.
5 rows � 41 columns
We create a DataFrame representing a list of shifts sorted by “wstart” and “duration”. This sorted list will be used to easily detect overlapping shifts.
Note that indices are reset after sorting so that the DataFrame can be indexed with respect to the index in the sorted list and not the original unsorted list. This is the purpose of the reset_index() operation which also adds a new column named “shiftId” with the original index.
Next, we state that for any pair of shifts that overlap in time, a nurse can be assigned to only one of the two.
#incompatible shift constraints: 640
When the nurse is on vacation, he cannot be assigned to any shift starting that day.
We use the pandas merge operation to create a join between the “df_vacations”, “df_shifts”, and “df_assigned” DataFrames. Each row of the resulting DataFrame contains the assignment decision variable corresponding to the matching (nurse, shift) pair.
# vacation forbids: 342 assignments
Some pairs of nurses get along particularly well, so we wish to assign them together as a team. In other words, for every such couple and for each shift, both assignment variables should always be equal. Either both nurses work the shift, or both do not.
In the same way we modeled vacations, we use the pandas merge operation to create a DataFrame for which each row contains the pair of nurse-shift assignment decision variables matching each association.
The associations constraint can now easily be formulated by iterating on the rows of the “df_preferred_assign” DataFrame.
Similarly, certain pairs of nurses do not get along well, and we want to avoid having them together on a shift. In other terms, for each shift, both nurses of an incompatible pair cannot be assigned together to the sift. Again, we state a logical OR between the two assignments: at most one nurse from the pair can work the shift.
We first create a DataFrame whose rows contain pairs of invalid
assignment decision variables, using the same pandas
operations as in the previous step.
The incompatibilities constraint can now easily be formulated, by iterating on the rows of the “df_incompatible_assign” DataFrame.
Constraints on work time¶
Regulations force constraints on the total work time over a week; and we compute this total work time in a new variable. We store the variable in an extra column in the nurse DataFrame.
The variable is declared as continuous though it contains only integer values. This is done to avoid adding unnecessary integer variables for the branch and bound algorithm. These variables are not true decision variables; they are used to express work constraints.
From a pandas perspective, we apply a function over the rows of the nurse DataFrame to create this variable and store it into a new column of the DataFrame.
Define total work time
Work time variables must be constrained to be equal to the sum of hours actually worked.
We use the pandas groupby operation to collect all assignment decision variables for each nurse in a separate series. Then, we iterate over nurses to post a constraint calculating the actual worktime for each nurse as the dot product of the series of nurse-shift assignments with the series of shift durations.
Model: nurses - number of variables: 1344 - binary=1312, integer=0, continuous=32 - number of constraints: 1547 - linear=1547 - parameters: defaults - problem type is: MILP
Maximum work time
For each nurse, we add a constraint to enforce the maximum work time for
a week. Again we use the
apply method, this time with an anonymous
name Anne worktime_Anne <= 40 Bethanie worktime_Bethanie <= 40 Betsy worktime_Betsy <= 40 Cathy worktime_Cathy <= 40 Cecilia worktime_Cecilia <= 40 Chris worktime_Chris <= 40 Cindy worktime_Cindy <= 40 David worktime_David <= 40 Debbie worktime_Debbie <= 40 Dee worktime_Dee <= 40 Gloria worktime_Gloria <= 40 Isabelle worktime_Isabelle <= 40 Jane worktime_Jane <= 40 Janelle worktime_Janelle <= 40 Janice worktime_Janice <= 40 Jemma worktime_Jemma <= 40 Joan worktime_Joan <= 40 Joyce worktime_Joyce <= 40 Jude worktime_Jude <= 40 Julie worktime_Julie <= 40 Juliet worktime_Juliet <= 40 Kate worktime_Kate <= 40 Nancy worktime_Nancy <= 40 Nathalie worktime_Nathalie <= 40 Nicole worktime_Nicole <= 40 Patricia worktime_Patricia <= 40 Patrick worktime_Patrick <= 40 Roberta worktime_Roberta <= 40 Suzanne worktime_Suzanne <= 40 Vickie worktime_Vickie <= 40 Wendie worktime_Wendie <= 40 Zoe worktime_Zoe <= 40 Name: worktime, dtype: object
Minimum requirement for shifts¶
Each shift requires a minimum number of nurses. For each shift, the sum over all nurses of assignments to this shift must be greater than the minimum requirement.
The pandas groupby operation is invoked to collect all assignment decision variables for each shift in a separate series. Then, we iterate over shifts to post the constraint enforcing the minimum number of nurse assignments for each shift.
Express the objective¶
The objective mixes different (and contradictory) KPIs.
The first KPI is the total salary cost, computed as the sum of work times over all nurses, weighted by pay rate.
We compute this KPI as an expression from the variables we previously defined by using the panda summation over the DOcplex objects.
DecisionKPI(name=Total salary cost,expr=25worktime_Anne+28worktime_Bethanie+17worktime_Betsy+17worktime_..)
Minimizing salary cost¶
In a preliminary version of the model, we minimize the total salary
cost. This is accomplished using the
Model: nurses - number of variables: 1344 - binary=1312, integer=0, continuous=32 - number of constraints: 1588 - linear=1588 - parameters: defaults - problem type is: MILP
Solve with Decision Optimization¶
Now we have everything we need to solve the model, using
Model.solve(). The following cell solves using your local CPLEX (if
any, and provided you have added it to your
CPXPARAM_Read_DataCheck 1 CPXPARAM_MIP_Tolerances_MIPGap 1.0000000000000001e-05 Tried aggregator 2 times. MIP Presolve eliminated 997 rows and 379 columns. MIP Presolve modified 90 coefficients. Aggregator did 41 substitutions. Reduced MIP has 550 rows, 922 columns, and 2862 nonzeros. Reduced MIP has 892 binaries, 0 generals, 0 SOSs, and 0 indicators. Presolve time = 0.00 sec. (3.68 ticks) Probing time = 0.00 sec. (0.50 ticks) Tried aggregator 1 time. Reduced MIP has 550 rows, 922 columns, and 2862 nonzeros. Reduced MIP has 892 binaries, 30 generals, 0 SOSs, and 0 indicators. Presolve time = 0.00 sec. (2.03 ticks) Probing time = 0.00 sec. (0.50 ticks) Clique table members: 479. MIP emphasis: balance optimality and feasibility. MIP search method: dynamic search. Parallel mode: deterministic, using up to 12 threads. Root relaxation solution time = 0.00 sec. (4.56 ticks) Nodes Cuts/ Node Left Objective IInf Best Integer Best Bound ItCnt Gap 0 0 28824.0000 48 28824.0000 473 0 0 28824.0000 62 Cuts: 98 649 0 0 28824.0000 35 Cuts: 44 716 0 0 28824.0000 41 Cuts: 55 795 * 0+ 0 29100.0000 28824.0000 0.95% * 0+ 0 29068.0000 28824.0000 0.84% 0 2 28824.0000 10 29068.0000 28824.0000 795 0.84% Elapsed time = 0.24 sec. (139.30 ticks, tree = 0.02 MB, solutions = 2) * 10+ 4 29014.0000 28824.0000 0.65% * 11+ 2 29010.0000 28824.0000 0.64% * 15+ 2 28982.0000 28824.0000 0.55% * 26+ 1 28944.0000 28824.0000 0.41% * 47+ 10 28936.0000 28824.0000 0.39% * 1611+ 1392 28888.0000 28824.0000 0.22% * 4006+ 3397 28842.0000 28824.0000 0.06% * 4152+ 3293 28824.0000 28824.0000 0.00% 4253 3414 28824.0000 6 28824.0000 28824.0000 73849 0.00% GUB cover cuts applied: 12 Cover cuts applied: 76 Flow cuts applied: 5 Mixed integer rounding cuts applied: 11 Zero-half cuts applied: 13 Lift and project cuts applied: 5 Root node processing (before b&c): Real time = 0.24 sec. (139.27 ticks) Parallel b&c, 12 threads: Real time = 0.47 sec. (270.80 ticks) Sync time (average) = 0.08 sec. Wait time (average) = 0.00 sec. ------------ Total (root+branch&cut) = 0.70 sec. (410.07 ticks) * model nurses solved with objective = 28824.000 * KPI: Total salary cost = 28824.000
Step 5: Investigate the solution and then run an example analysis¶
We take advantage of pandas to analyze the results. First we store the solution values of the assignment variables into a new pandas Series.
solution_value on a DOcplex variable returns its value in
the solution (provided the model has been successfully solved).
5 rows � 41 columns
Analyzing how worktime is distributed¶
Let’s analyze how worktime is distributed among nurses.
First, we compute the global average work time as the total minimum requirement in hours, divided by number of nurses.
* theoretical average work time is 39 h
Let’s analyze the series of deviations to the average, stored in a pandas Series.
* the sum of absolute deviations from mean is 58.0
To see how work time is distributed among nurses, print a histogram of work time values. Note that, as all time data are integers, work times in the solution can take only integer values.
Text(0.5, 0, 'worktime')
How shifts are distributed¶
Let’s now analyze the solution from the number of shifts perspective. How many shifts does each nurse work? Are these shifts fairly distributed amongst nurses?
We compute a new column in our result DataFrame for the number of shifts worked, by summing rows (the “axis=1” argument in the sum() call indicates to pandas that each sum is performed by row instead of column):
Text(0, 0.5, '#shifts worked')
We see that one nurse works significantly fewer shifts than others do. What is the average number of shifts worked by a nurse? This is equal to the total demand divided by the number of nurses.
Of course, this yields a fractional number of shifts that is not practical, but nonetheless will help us quantify the fairness in shift distribution.
-- expected avg #shifts worked is 6.875 -- total absolute deviation to mean #shifts is 16.25
Introducing a fairness goal¶
As the above diagram suggests, the distribution of shifts could be improved. We implement this by adding one extra objective, fairness, which balances the shifts assigned over nurses.
Note that we can edit the model, that is add (or remove) constraints, even after it has been solved.
Step #1 : Introduce three new variables per nurse to model the¶
number of shifts worked and positive and negative deviations to the average.
Step #3 : Define KPIs to measure the result after solve.¶
Finally, let’s modify the objective by adding the sum of
over_worked and under_worked to the previous objective.
Note: The definitions of
described above are not sufficient to give them an unambiguous value.
However, as all these variables are minimized, CPLEX ensures that these
variables take the minimum possible values in the solution.
Our modified model is ready to solve.
log_output=True parameter tells CPLEX to print the log on the
CPXPARAM_Read_DataCheck 1 CPXPARAM_MIP_Tolerances_MIPGap 1.0000000000000001e-05 1 of 31 MIP starts provided solutions. MIP start 'm1' defined initial solution with objective 28840.2500. Tried aggregator 2 times. MIP Presolve eliminated 997 rows and 379 columns. MIP Presolve modified 90 coefficients. Aggregator did 73 substitutions. Reduced MIP has 582 rows, 986 columns, and 3859 nonzeros. Reduced MIP has 892 binaries, 0 generals, 0 SOSs, and 0 indicators. Presolve time = 0.02 sec. (4.35 ticks) Probing time = 0.00 sec. (0.59 ticks) Tried aggregator 1 time. MIP Presolve eliminated 2 rows and 4 columns. Reduced MIP has 580 rows, 982 columns, and 3814 nonzeros. Reduced MIP has 892 binaries, 30 generals, 0 SOSs, and 0 indicators. Presolve time = 0.00 sec. (2.41 ticks) Probing time = 0.00 sec. (0.58 ticks) Clique table members: 479. MIP emphasis: balance optimality and feasibility. MIP search method: dynamic search. Parallel mode: deterministic, using up to 12 threads. Root relaxation solution time = 0.01 sec. (11.48 ticks) Nodes Cuts/ Node Left Objective IInf Best Integer Best Bound ItCnt Gap * 0+ 0 28840.2500 0.0000 100.00% 0 0 28827.9167 76 28840.2500 28827.9167 885 0.04% 0 0 28829.2500 51 28840.2500 Cuts: 89 1053 0.04% 0 0 28829.9063 59 28840.2500 Cuts: 107 1359 0.04% 0 0 28831.0000 33 28840.2500 Cuts: 55 1530 0.03% 0 0 28831.0000 45 28840.2500 Cuts: 36 1649 0.03% 0 0 28831.0000 35 28840.2500 Cuts: 8 1715 0.03% 0 0 28831.0000 34 28840.2500 Cuts: 29 1783 0.03% * 0+ 0 28831.2500 28831.0000 0.00% GUB cover cuts applied: 19 Cover cuts applied: 4 Flow cuts applied: 21 Mixed integer rounding cuts applied: 69 Zero-half cuts applied: 14 Gomory fractional cuts applied: 4 Root node processing (before b&c): Real time = 0.36 sec. (211.92 ticks) Parallel b&c, 12 threads: Real time = 0.00 sec. (0.00 ticks) Sync time (average) = 0.00 sec. Wait time (average) = 0.00 sec. ------------ Total (root+branch&cut) = 0.36 sec. (211.92 ticks) * model nurses solved with objective = 28831.250 * KPI: Total salary cost = 28824.000 * KPI: Total over-worked = 3.625 * KPI: Total under-worked = 3.625
Analyzing new results¶
Let’s recompute the new total deviation from average on this new solution.
-- total absolute deviation to mean #shifts is now 7.25 down from 16.25
5 rows � 42 columns
Let’s print the new histogram of shifts worked.
<matplotlib.axes._subplots.AxesSubplot at 0x279df51e710>
The breakdown of shifts over nurses is much closer to the average than it was in the previous version.
But what would be the minimal fairness level?¶
But what is the absolute minimum for the deviation to the ideal average number of shifts? CPLEX can tell us: simply minimize only the the total deviation from average, ignoring the salary cost. Of course this is unrealistic, but it will help us quantify how far our fairness result is to the absolute optimal fairness.
We modify the objective and solve for the third time.
* model nurses solved with objective = 4.000 * KPI: Total salary cost = 29606.000 * KPI: Total over-worked = 4.000 * KPI: Total under-worked = 0.000
In the fairness-optimal solution, we have zero under-average shifts and 4 over-average. Salary cost is now higher than the previous value of 28884 but this was expected as salary cost was not part of the objective.
To summarize, the absolute minimum for this measure of fairness is 4, and we have found a balance with fairness=7.
Finally, we display the histogram for this optimal-fairness solution.
<matplotlib.axes._subplots.AxesSubplot at 0x279e05915f8>
In the above figure, all nurses but one are assigned the average of 7 shifts, which is what we expected.
You learned how to set up and use IBM Decision Optimization CPLEX Modeling for Python to formulate a Mathematical Programming model and solve it with IBM Decision Optimization on Cloud.