gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:06 25 4
gpt4 key购买 nike

我希望创建一个分布来显示员工可以上类的时间。类似于此图,可在此链接中找到 staff distribution .

Matrix Distribution

为实现这一点,我创建了 staff_availability_df,其中包含要从中挑选的员工数量,可在 ['Person'] 列中找到。他们可以工作的 min - max 小时数,他们得到的报酬是多少都有这样的标签。 The available times they can work are separated into hours ['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 显示整个类次的时间 和我需要的所需人员

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]

我希望使用这些函数来创建一个线性规划矩阵,它返回每个员工可以工作的时间的分布。但我希望使用 15 分钟的片段以及几个小时。例如注意:此导出将延长至 3:30am。所以它将包含 79 个段。

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

enter image description here

有几个工作人员可用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解决整数规划问题

现在,我们可以让 pulp 开始工作了:以最小化成本为目标设置问题,并逐一添加您提到的约束,请参阅注释代码。 staffed 现在是一个 pulp-dictionary,其中包含一个人是否在某个时间段(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/的代码这是一个很好的 PuLP 和线性规划教程,所以一定要检查一下。

附录:您的要求不可行。

根据您的条件,这实际上将返回 'Infeasible'。很容易看出这是为什么: Required staff vs available staff
您可以看到在最后几个时间段中需要的工作人员多于可用的工作人员。此图由以下人员创建:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com