import pip
REQUIRED_MINIMUM_PANDAS_VERSION = '0.17.1'
try:
    import pandas as pd
    assert pd.__version__ >= REQUIRED_MINIMUM_PANDAS_VERSION
except:
    raise Exception("Version %s or above of Pandas is required to run this notebook" % REQUIRED_MINIMUM_PANDAS_VERSION)

"""
Explanation: 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.

This notebook is part of Prescriptive Analytics for Python
It requires either an installation of CPLEX Optimizers or it can be run on IBM Cloud Pak for Data as a Service (Sign up for a free IBM Cloud account
and you can start using IBM Cloud Pak for Data as a Service right away).
CPLEX is available on <i>IBM Cloud Pack for Data</i> and <i>IBM Cloud Pak for Data as a Service</i>:
   - <i>IBM Cloud Pak for Data as a Service</i>: Depends on the runtime used:
        - <i>Python 3.x</i> runtime: Community edition
        - <i>Python 3.x + DO</i> runtime: full edition
   - <i>Cloud Pack for Data</i>: Community edition is installed by default. Please install DO addon in Watson Studio Premium for the full edition

Table of contents:

Describe the business problem
How decision optimization (prescriptive analytics) can help
Use decision optimization
Step 1: Import the library
Step 2: Model the data
Step 3: Prepare the data
Step 4: Set up the prescriptive model
Define the decision variables
Express the business constraints
Express the objective
Solve with Decision Optimization


Step 5: Investigate the solution and run an example analysis


Summary


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.
<br/>


<u>With prescriptive analytics, you can:</u> 

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.
End of explanation
"""


import sys
try:
    import docplex.mp
except:
    raise Exception('Please install docplex. See https://pypi.org/project/docplex/')

"""
Explanation: 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).
End of explanation
"""


CSS = """
body {
    margin: 0;
    font-family: Helvetica;
}
table.dataframe {
    border-collapse: collapse;
    border: none;
}
table.dataframe tr {
    border: none;
}
table.dataframe td, table.dataframe th {
    margin: 0;
    border: 1px solid white;
    padding-left: 0.25em;
    padding-right: 0.25em;
}
table.dataframe th:not(:empty) {
    background-color: #fec;
    text-align: left;
    font-weight: normal;
}
table.dataframe tr:nth-child(2) th:empty {
    border-left: none;
    border-right: 1px dashed #888;
}
table.dataframe td {
    border: 2px solid #ccf;
    background-color: #f4f4ff;
}
    table.dataframe thead th:first-child {
        display: none;
    }
    table.dataframe tbody th {
        display: none;
    }
"""

from IPython.core.display import HTML
HTML('<style>{}</style>'.format(CSS))

from IPython.display import display

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

# This notebook requires pandas to work
import pandas as pd
from pandas import DataFrame

# Make sure that xlrd package, which is a pandas optional dependency, is installed
# This package is required for Excel I/O
try:
    import xlrd
except:
    if hasattr(sys, 'real_prefix'):
        #we are in a virtual env.
        !pip install xlrd 
    else:
        !pip install --user xlrd      

# Use pandas to read the file, one tab for each table.
data_url = "https://github.com/IBMDecisionOptimization/docplex-examples/blob/master/examples/mp/jupyter/nurses_data.xls?raw=true"
nurse_xls_file = pd.ExcelFile(data_url)

df_skills = nurse_xls_file.parse('Skills')
df_depts = nurse_xls_file.parse('Departments')
df_shifts = nurse_xls_file.parse('Shifts')
# Rename df_shifts index
df_shifts.index.name = 'shiftId'

# Index is column 0: name
df_nurses = nurse_xls_file.parse('Nurses', header=0, index_col=0)
df_nurse_skills = nurse_xls_file.parse('NurseSkills')
df_vacations = nurse_xls_file.parse('NurseVacations')
df_associations = nurse_xls_file.parse('NurseAssociations')
df_incompatibilities = nurse_xls_file.parse('NurseIncompatibilities')

# Display the nurses dataframe
print("#nurses = {}".format(len(df_nurses)))
print("#shifts = {}".format(len(df_shifts)))
print("#vacations = {}".format(len(df_vacations)))

"""
Explanation: 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.
End of explanation
"""


# maximum work time (in hours)
max_work_time = 40

# maximum number of shifts worked in a week.
max_nb_shifts = 5

"""
Explanation: 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.
End of explanation
"""


df_shifts

"""
Explanation: Shifts are stored in a separate DataFrame.
End of explanation
"""


days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
day_of_weeks = dict(zip(days, range(7)))

# utility to convert a day string e.g. "Monday" to an integer in 0..6
def day_to_day_of_week(day):
    return day_of_weeks[day.strip().lower()]

# for each day name, we normalize it by stripping whitespace and converting it to lowercase
# " Monday" -> "monday"
df_shifts["dow"] = df_shifts.day.apply(day_to_day_of_week)
df_shifts

"""
Explanation: 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.
Sub-step #1
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).
End of explanation
"""


df_shifts["wstart"] = df_shifts.start_time + 24 * df_shifts.dow

"""
Explanation: Sub-step #2 : Compute the absolute start time of each shift.
Computing the start time in the week is easy: just add 24*dow to column start_time. The result is stored in a new column wstart.
End of explanation
"""


# an auxiliary function to calculate absolute end time of a shift
def calculate_absolute_endtime(start, end, dow):
    return 24*dow + end + (24 if start>=end else 0)

# store the results in a new column
df_shifts["wend"] = df_shifts.apply(lambda row: calculate_absolute_endtime(
        row.start_time, row.end_time, row.dow), axis=1)

"""
Explanation: 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&gt;= 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 lambda 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.
End of explanation
"""


df_shifts["duration"] = df_shifts.wend - df_shifts.wstart

"""
Explanation: 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 duration.
End of explanation
"""


# also compute minimum demand in nurse-hours
df_shifts["min_demand"] = df_shifts.min_req * df_shifts.duration

# finally check the modified shifts dataframe
df_shifts

"""
Explanation: 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 min_demand.
Finally, we display the updated shifts DataFrame with all calculated columns.
End of explanation
"""


from docplex.mp.model import Model
mdl = Model(name="nurses")

"""
Explanation: Step 4: Set up the prescriptive model
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.
End of explanation
"""


# first global collections to iterate upon
all_nurses = df_nurses.index.values
all_shifts = df_shifts.index.values

# the assignment variables.
assigned = mdl.binary_var_matrix(keys1=all_nurses, keys2=all_shifts, name="assign_%s_%s")

"""
Explanation: 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.
End of explanation
"""


# Organize decision variables in a DataFrame
df_assigned = DataFrame({'assigned': assigned})
df_assigned.index.names=['all_nurses', 'all_shifts']

# Re-organize the Data Frame as a pivot table with nurses as row index and shifts as columns:
df_assigned_pivot = df_assigned.unstack(level='all_shifts')

# Create a pivot using nurses and shifts index as dimensions
#df_assigned_pivot = df_assigned.reset_index().pivot(index='all_nurses', columns='all_shifts', values='assigned')

# Display first rows of the pivot table
df_assigned_pivot.head()

"""
Explanation: Express the business constraints
Overlapping shifts
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.
End of explanation
"""


# Create a Data Frame representing a list of shifts sorted by wstart and duration.
# One keeps only the three relevant columns: 'shiftId', 'wstart' and 'wend' in the resulting Data Frame 
df_sorted_shifts = df_shifts.sort_values(['wstart','duration']).reset_index()[['shiftId', 'wstart', 'wend']]

# Display the first rows of the newly created Data Frame
df_sorted_shifts.head()

"""
Explanation: 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.
End of explanation
"""


number_of_incompatible_shift_constraints = 0
for shift in df_sorted_shifts.itertuples():
    # Iterate over following shifts
    # 'shift[0]' contains the index of the current shift in the df_sorted_shifts Data Frame
    for shift_2 in df_sorted_shifts.iloc[shift[0] + 1:].itertuples():
        if (shift_2.wstart < shift.wend):
            # Iterate over all nurses to force incompatible assignment for the current pair of overlapping shifts
            for nurse_assignments in df_assigned_pivot.iloc[:, [shift.shiftId, shift_2.shiftId]].itertuples():
                # this is actually a logical OR
                mdl.add_constraint(nurse_assignments[1] + nurse_assignments[2] <= 1)
                number_of_incompatible_shift_constraints += 1
        else:
            # No need to test overlap with following shifts
            break
print("#incompatible shift constraints: {}".format(number_of_incompatible_shift_constraints))

"""
Explanation: Next, we state that for any pair of shifts that overlap in time, a nurse can be assigned to only one of the two.
End of explanation
"""


# Add 'day of week' column to vacations Data Frame
df_vacations['dow'] = df_vacations.day.apply(day_to_day_of_week)

# Join 'df_vacations', 'df_shifts' and 'df_assigned' Data Frames to create the list of 'forbidden' assigments.
# The 'reset_index()' function is invoked to move 'shiftId' index as a column in 'df_shifts' Data Frame, and
# to move the index pair ('all_nurses', 'all_shifts') as columns in 'df_assigned' Data Frame.
# 'reset_index()' is invoked so that a join can be performed between Data Frame, based on column names.
df_assigned_reindexed = df_assigned.reset_index()
df_vacation_forbidden_assignments = df_vacations.merge(df_shifts.reset_index()[['dow', 'shiftId']]).merge(
    df_assigned_reindexed, left_on=['nurse', 'shiftId'], right_on=['all_nurses', 'all_shifts'])

# Here are the first few rows of the resulting Data Frames joins
df_vacation_forbidden_assignments.head()

for forbidden_assignment in df_vacation_forbidden_assignments.itertuples():
    # to forbid an assignment just set the variable to zero.
    mdl.add_constraint(forbidden_assignment.assigned == 0)
print("# vacation forbids: {} assignments".format(len(df_vacation_forbidden_assignments)))

"""
Explanation: Vacations
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.
End of explanation
"""


# Join 'df_assignment' Data Frame twice, based on associations to get corresponding decision variables pairs for all shifts
# The 'suffixes' parameter in the second merge indicates our preference for updating the name of columns that occur both
# in the first and second argument Data Frames (in our case, these columns are 'all_nurses' and 'assigned').
df_preferred_assign = df_associations.merge(
    df_assigned_reindexed, left_on='nurse1', right_on='all_nurses').merge(
    df_assigned_reindexed, left_on=['nurse2', 'all_shifts'], right_on=['all_nurses', 'all_shifts'], suffixes=('_1','_2'))

# Here are the first few rows of the resulting Data Frames joins
df_preferred_assign.head()

"""
Explanation: Associations
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.
End of explanation
"""


for preferred_assign in df_preferred_assign.itertuples():
    mdl.add_constraint(preferred_assign.assigned_1 == preferred_assign.assigned_2)

"""
Explanation: The associations constraint can now easily be formulated by iterating on the rows of the "df_preferred_assign" DataFrame.
End of explanation
"""


# Join assignment Data Frame twice, based on incompatibilities Data Frame to get corresponding decision variables pairs
#  for all shifts
df_incompatible_assign = df_incompatibilities.merge(
    df_assigned_reindexed, left_on='nurse1', right_on='all_nurses').merge(
    df_assigned_reindexed, left_on=['nurse2', 'all_shifts'], right_on=['all_nurses', 'all_shifts'], suffixes=('_1','_2'))

# Here are the first few rows of the resulting Data Frames joins
df_incompatible_assign.head()

"""
Explanation: Incompatibilities
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 merge operations as in the previous step.
End of explanation
"""


for incompatible_assign in df_incompatible_assign.itertuples():
    mdl.add_constraint(incompatible_assign.assigned_1 + incompatible_assign.assigned_2 <= 1)

"""
Explanation: The incompatibilities constraint can now easily be formulated, by iterating on the rows of the "df_incompatible_assign" DataFrame.
End of explanation
"""


# auxiliary function to create worktime variable from a row
def make_var(row, varname_fmt):
    return mdl.continuous_var(name=varname_fmt % row.name, lb=0)

# apply the function over nurse rows and store result in a new column
df_nurses["worktime"] = df_nurses.apply(lambda r: make_var(r, "worktime_%s"), axis=1)

# display nurse dataframe
df_nurses

"""
Explanation: 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.
End of explanation
"""


# Use pandas' groupby operation to enforce constraint calculating worktime for each nurse as the sum of all assigned
#  shifts times the duration of each shift
for nurse, nurse_assignments in df_assigned.groupby(level='all_nurses'):
    mdl.add_constraint(df_nurses.worktime[nurse] == mdl.dot(nurse_assignments.assigned, df_shifts.duration))
                       
# print model information and check we now have 32 extra continuous variables
mdl.print_information()

"""
Explanation: 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.
End of explanation
"""


# we use pandas' apply() method to set an upper bound on all worktime variables.
def set_max_work_time(v):
    v.ub = max_work_time
    # Optionally: return a string for fancy display of the constraint in the Output cell
    return str(v) + ' <= ' + str(v.ub)

df_nurses["worktime"].apply(convert_dtype=False, func=set_max_work_time)

"""
Explanation: 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 lambda function.
End of explanation
"""


# Use pandas' groupby operation to enforce minimum requirement constraint for each shift
for shift, shift_nurses in df_assigned.groupby(level='all_shifts'):
    mdl.add_constraint(mdl.sum(shift_nurses.assigned) >= df_shifts.min_req[shift])

"""
Explanation: 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.
End of explanation
"""


# again leverage pandas to create a series of expressions: costs of each nurse
total_salary_series = df_nurses.worktime * df_nurses.pay_rate

# compute global salary cost using pandas sum()
# Note that the result is a DOcplex expression: DOcplex if fully compatible with pandas
total_salary_cost = total_salary_series.sum()
mdl.add_kpi(total_salary_cost, "Total salary cost")

"""
Explanation: 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.
End of explanation
"""


mdl.minimize(total_salary_cost)
mdl.print_information()

"""
Explanation: Minimizing salary cost
In a preliminary version of the model, we minimize the total salary cost. This is accomplished
using the Model.minimize() method.
End of explanation
"""


# Set Cplex mipgap to 1e-5 to enforce precision to be of the order of a unit (objective value magnitude is ~1e+5).
mdl.parameters.mip.tolerances.mipgap = 1e-5

s = mdl.solve(log_output=True)
assert s, "solve failed"
mdl.report()

"""
Explanation: 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 PYTHONPATH variable).
End of explanation
"""


# Create a pandas Series containing actual shift assignment decision variables value
s_assigned = df_assigned.assigned.apply(lambda v: v.solution_value)

# Create a pivot table by (nurses, shifts), using pandas' "unstack" method to transform the 'all_shifts' row index
#  into columns
df_res = s_assigned.unstack(level='all_shifts')

# Display the first few rows of the resulting pivot table
df_res.head()

"""
Explanation: 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.
Calling solution_value on a DOcplex variable returns its value in the solution (provided the model has been successfully solved).
End of explanation
"""


s_demand  = df_shifts.min_req * df_shifts.duration
total_demand = s_demand.sum()
avg_worktime = total_demand / float(len(all_nurses))
print("* theoretical average work time is {0:g} h".format(avg_worktime))

"""
Explanation: 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.
End of explanation
"""


# a pandas series of worktimes solution values
s_worktime = df_nurses.worktime.apply(lambda v: v.solution_value)

# returns a new series computed as deviation from average
s_to_mean = s_worktime - avg_worktime

# take the absolute value
s_abs_to_mean = s_to_mean.apply(abs)


total_to_mean = s_abs_to_mean.sum()
print("* the sum of absolute deviations from mean is {}".format(total_to_mean))

"""
Explanation: Let's analyze the series of deviations to the average, stored in a pandas Series.
End of explanation
"""


import matplotlib.pyplot as plt
%matplotlib inline

# we can also plot as a histogram the distribution of worktimes
s_worktime.plot.hist(color='LightBlue')
plt.xlabel("worktime")

"""
Explanation: 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.
End of explanation
"""


# a pandas series of #shifts worked
df_worked = df_res[all_shifts].sum(axis=1)
df_res["worked"] = df_worked

df_worked.plot.hist(color="gold", xlim=(0,10))
plt.ylabel("#shifts worked")

"""
Explanation: 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):
End of explanation
"""


avg_worked = df_shifts["min_req"].sum() / float(len(all_nurses))
print("-- expected avg #shifts worked is {}".format(avg_worked))

worked_to_avg = df_res["worked"] - avg_worked
total_to_mean = worked_to_avg.apply(abs).sum()
print("-- total absolute deviation to mean #shifts is {}".format(total_to_mean))

"""
Explanation: 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.
End of explanation
"""


# add two extra variables per nurse: deviations above and below average
df_nurses["worked"]      = df_nurses.apply(lambda r: make_var(r, "worked%s"), axis=1)
df_nurses["overworked"]  = df_nurses.apply(lambda r: make_var(r, "overw_%s"), axis=1)
df_nurses["underworked"] = df_nurses.apply(lambda r: make_var(r, "underw_%s"), axis=1)

"""
Explanation: 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.
End of explanation
"""


# Use the pandas groupby operation to enforce the constraint calculating number of worked shifts for each nurse
for nurse, nurse_assignments in df_assigned.groupby(level='all_nurses'):
    # nb of worked shifts is sum of assigned shifts
    mdl.add_constraint(df_nurses.worked[nurse] == mdl.sum(nurse_assignments.assigned))

for nurse in df_nurses.itertuples():
    # nb worked is average + over - under
    mdl.add_constraint(nurse.worked == avg_worked + nurse.overworked - nurse.underworked)

"""
Explanation: Step #2 : Post the constraint that links these variables together.
End of explanation
"""


# finally, define kpis for over and under average quantities
total_overw = mdl.sum(df_nurses["overworked"])
mdl.add_kpi(total_overw, "Total over-worked")
total_underw = mdl.sum(df_nurses["underworked"])
mdl.add_kpi(total_underw, "Total under-worked")

"""
Explanation: Step #3 : Define KPIs to measure the result after solve.
End of explanation
"""


mdl.minimize(total_salary_cost + total_overw + total_underw)  # incorporate over_worked and under_worked in objective

"""
Explanation: Finally, let's modify the objective by adding the sum of over_worked and under_worked to the previous objective.
Note: The definitions of over_worked and under_worked as 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.
End of explanation
"""


sol2 = mdl.solve(log_output=True)  # solve again and get a new solution
assert sol2, "Solve failed"
mdl.report()

"""
Explanation: Our modified model is ready to solve.
The log_output=True parameter tells CPLEX to print the log on the standard output.
End of explanation
"""


# Create a pandas Series containing actual shift assignment decision variables value
s_assigned2 = df_assigned.assigned.apply(lambda v: v.solution_value)

# Create a pivot table by (nurses, shifts), using pandas' "unstack" method to transform the 'all_shifts' row index
#  into columns
df_res2 = s_assigned2.unstack(level='all_shifts')

# Add a new column to the pivot table containing the #shifts worked by summing over each row
df_res2["worked"] = df_res2[all_shifts].sum(axis=1)

# total absolute deviation from average is directly read on expressions
new_total_to_mean = total_overw.solution_value + total_underw.solution_value
print("-- total absolute deviation to mean #shifts is now {0} down from {1}".format(new_total_to_mean, total_to_mean))

# Display the first few rows of the result Data Frame
df_res2.head()

"""
Explanation: Analyzing new results
Let's recompute the new total deviation from average on this new solution.
End of explanation
"""


df_res2["worked"].plot(kind="hist", color="gold", xlim=(3,8))

"""
Explanation: Let's print the new histogram of shifts worked.
End of explanation
"""


mdl.minimize(total_overw + total_underw)
assert mdl.solve(), "solve failed"
mdl.report()

"""
Explanation: 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 (using the usual necessary update for DOcplexcloud credentials).
End of explanation
"""


# Create a pandas Series containing actual shift assignment decision variables value
s_assigned_fair = df_assigned.assigned.apply(lambda v: v.solution_value)

# Create a pivot table by (nurses, shifts), using pandas' "unstack" method to transform the 'all_shifts' row index
#  into columns
df_res_fair = s_assigned_fair.unstack(level='all_shifts')

# Add a new column to the pivot table containing the #shifts worked by summing over each row
df_res_fair["solution_value_fair"] = df_res_fair[all_shifts].sum(axis=1)
df_res_fair["worked"] = df_res_fair[all_shifts].sum(axis=1)
df_res_fair["worked"].plot.hist(color="plum", xlim=(3,8))

"""
Explanation: 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.
End of explanation
"""


