我希望创建一个分配来显示员工可上班的时间。与此图相似,在此链接staff distribution中可以找到该图。

python - 创建可用值的分布-Python-LMLPHP

为此,我创建了staff_availability_df,其中包含要选择的员工数量,该数量可在['Person']列中找到。他们可以工作的min - max小时,所获得的报酬是这样的。他们可以工作的可用时间分为小时数['Availability_Hr'],该小时数表示他们可以工作的时间,以小时表示。因此,第一个人是'8-18',也就是8:00:00am - 18:00:00pm['Availability_15min_Seg']基本上是相同的,但小时数分为4个部分。因此,第一个人是'1-41',又是8:00:00am - 18:00:00pm

注意:标准班次在8:00:00am - 3:30:00am之间运行,因此大约需要20个小时。

staff_requirements_df在整个班次中显示Time以及我需要的必需People

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates

#This is the employee availability:
staff_availability = pd.DataFrame({
    'Person' : ['C1','C2','C3','C4','C5','C6','C7','C8','C9','C10','C11'],
    'MinHours' : [5,5,5,5,5,5,5,5,5,5,5],
    'MaxHours' : [10,10,10,10,10,10,10,10,10,10,10],
    'HourlyWage' : [26,26,26,26,26,26,26,26,26,26,26],
    'Availability_Hr' : ['8-18','8-18','8-18','9-18','9-18','9-18','12-1','12-1','17-3','17-3','17-3'],
    'Availability_15min_Seg' : ['1-41','1-41','1-41','5-41','5-41','5-41','17-69','17-69','37-79','37-79','37-79'],
    })

#These are the staffing requirements:
staffing_requirements = pd.DataFrame({
    'Time' : ['0/1/1900 8:00:00','0/1/1900 9:59:00','0/1/1900 10:00:00','0/1/1900 12:29:00','0/1/1900 12:30:00','0/1/1900 13:00:00','0/1/1900 13:02:00','0/1/1900 13:15:00','0/1/1900 13:20:00','0/1/1900 18:10:00','0/1/1900 18:15:00','0/1/1900 18:20:00','0/1/1900 18:25:00','0/1/1900 18:45:00','0/1/1900 18:50:00','0/1/1900 19:05:00','0/1/1900 19:07:00','0/1/1900 21:57:00','0/1/1900 22:00:00','0/1/1900 22:30:00','0/1/1900 22:35:00','1/1/1900 3:00:00','1/1/1900 3:05:00','1/1/1900 3:20:00','1/1/1900 3:25:00'],
    'People' : [1,1,2,2,3,3,2,2,3,3,4,4,3,3,2,2,3,3,4,4,3,3,2,2,1],
     })


我已使用以下功能将8:00:00am - 3:30:00am之间的15分钟细分中的人员编制要求导出。每15分钟分配给string 'T'。所以T1 = 8:00:00amT79 = 3:00:00am

staffing_requirements['Time'] = ['/'.join([str(int(x.split('/')[0])+1)] + x.split('/')[1:]) for x in staffing_requirements['Time']]
staffing_requirements['Time'] = pd.to_datetime(staffing_requirements['Time'], format='%d/%m/%Y %H:%M:%S')
formatter = dates.DateFormatter('%Y-%m-%d %H:%M:%S')

staffing_requirements = staffing_requirements.groupby(pd.Grouper(freq='15T',key='Time'))['People'].max().ffill()
staffing_requirements = staffing_requirements.reset_index(level=['Time'])

staffing_requirements.insert(2, 'T', range(1, 1 + len(staffing_requirements)))
staffing_requirements['T'] = 'T' + staffing_requirements['T'].astype(str)

st_req = staffing_requirements['People'].tolist()

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 3.0, 2.0]


我希望使用这些功能来创建一个linear programming matrix,它返回每个员工可工作时间的分布。但我希望使用15分钟的时间段和小时。例如注意:此导出将扩展到3:30am。因此它将包含79个细分。

注意:要明确。我希望返回分发时间表,以便将来使用。不只是一个数字。

python - 创建可用值的分布-Python-LMLPHP

有一些使用mixed-integer linear programming的人员可用example 1 example 2方法,但是他们使用的是封闭源代码软件。我希望将其翻译成Python。

最佳答案

对于整数编程而言,这确实是一项伟大的工作。您可以使用pulp,您首先需要通过命令行进行安装,例如pip install pulp

数据处理以确保成功

然后,首先确保您的DataFrames处于最佳形状,以便我们解决问题:

# Since timeslots for staffing start counting at 1, also make the
# DataFrame index start counting at 1
staffing_requirements.index = range(1, len(staffing_requirements) + 1)
print(staffing_requirements.tail())

staff_availability.set_index('Person')

staff_costs = staff_availability.set_index('Person')[['MinHours', 'MaxHours', 'HourlyWage']]
availability = staff_availability.set_index('Person')[['Availability_15min_Seg']]
availability[['first_15min', 'last_15min']] =  availability['Availability_15min_Seg'].str.split('-', expand=True).astype(int)

availability_per_member =  [pd.DataFrame(1, columns=[idx], index=range(row['first_15min'], row['last_15min']+1))
 for idx, row in availability.iterrows()]

availability_per_member = pd.concat(availability_per_member, axis='columns').fillna(0).astype(int).stack()
availability_per_member.index.names = ['Timeslot', 'Person']
availability_per_member = (availability_per_member.to_frame()
                            .join(staff_costs[['HourlyWage']])
                            .rename(columns={0: 'Available'}))


现在,availability_per_member是一个MultiIndex DataFrame,每个时隙每个人只有一行,表明他/她的可用性和工资:

#                 Available  HourlyWage
#Timeslot Person
#1        C1              1          26
#         C2              1          26
#         C3              1          26
#         C4              0          26
#         C5              0          26


另外,我们稍微修改了必要条件,以便实际上可以解决问题;为何需要这样做,请参阅附录

import numpy as np
np.random.seed(42)
staffing_requirements['People'] = np.random.randint(1, 4, size=len(staffing_requirements))
staff_costs['MinHours'] = 3


使用pulp解决整数编程问题

现在,我们可以开始工作了:设置问题以最小化成本为目标,并逐一添加您提到的约束,请参阅注释的代码。 staffed现在是一本纸浆字典,其中包含某人在特定时间段(0或1)的工作人员

import pulp
prob = pulp.LpProblem('CreateStaffing', pulp.LpMinimize) # Minimize costs

timeslots = staffing_requirements.index
persons = availability_per_member.index.levels[1]

# A member is either staffed or is not at a certain timeslot
staffed = pulp.LpVariable.dicts("staffed",
                                   ((timeslot, staffmember) for timeslot, staffmember
                                    in availability_per_member.index),
                                     lowBound=0,
                                     cat='Binary')

# Objective = cost (= sum of hourly wages)
prob += pulp.lpSum(
    [staffed[timeslot, staffmember] * availability_per_member.loc[(timeslot, staffmember), 'HourlyWage']
    for timeslot, staffmember in availability_per_member.index]
)

# Staff the right number of people
for timeslot in timeslots:
    prob += (sum([staffed[(timeslot, person)] for person in persons])
    == staffing_requirements.loc[timeslot, 'People'])


# Do not staff unavailable persons
for timeslot in timeslots:
    for person in persons:
        if availability_per_member.loc[(timeslot, person), 'Available'] == 0:
            prob += staffed[timeslot, person] == 0

# Do not underemploy people
for person in persons:
    prob += (sum([staffed[(timeslot, person)] for timeslot in timeslots])
    >= staff_costs.loc[person, 'MinHours']*4) # timeslot is 15 minutes => 4 timeslots = hour

# Do not overemploy people
for person in persons:
    prob += (sum([staffed[(timeslot, person)] for timeslot in timeslots])
    <= staff_costs.loc[person, 'MaxHours']*4) # timeslot is 15 minutes => 4 timeslots = hour


然后,让pulp解决问题就可以了:

prob.solve()
print(pulp.LpStatus[prob.status])

output = []
for timeslot, staffmember in staffed:
    var_output = {
        'Timeslot': timeslot,
        'Staffmember': staffmember,
        'Staffed': staffed[(timeslot, staffmember)].varValue,
    }
    output.append(var_output)
output_df = pd.DataFrame.from_records(output)#.sort_values(['timeslot', 'staffmember'])
output_df.set_index(['Timeslot', 'Staffmember'], inplace=True)
if pulp.LpStatus[prob.status] == 'Optimal':
    print(output_df)


现在,这将返回一个DataFrame output_df,每个时隙和每个人都包含他们是否配备了人员:

#                      Staffed
#Timeslot Staffmember
#1        C1               1.0
#         C2               1.0
#         C3               1.0
#         C4               0.0
#         C5               0.0
#         C6               0.0
#         C7               0.0
#         C8               0.0
#         C9               0.0
#         C10              0.0
#         C11              0.0
#2        C1               1.0
#         C2               1.0


我已经修改了http://benalexkeen.com/linear-programming-with-python-and-pulp-part-5/的代码,这对制浆和线性编程是一个很好的教程,因此请务必将其检出。

附录:您的要求不可行。

根据您的条件,这实际上将返回'Infeasible'。很容易看出为什么是这样的:
python - 创建可用值的分布-Python-LMLPHP
您会看到所需的工作人员比最近几个时隙中可用的工作人员多。该图是由以下人员创建的:

fig, ax = plt.subplots()
staffing_requirements.plot(y='People', ax=ax, label='Required', drawstyle='steps-mid')
availability_per_member.groupby(level='Timeslot')['Available'].sum().plot(ax=ax,
                               label='Available', drawstyle='steps-mid')
plt.legend()

关于python - 创建可用值的分布-Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55330016/

10-10 16:44