用python写一段混合流水车间调度问题的甘特图代码
时间: 2023-10-11 15:10:12 浏览: 171
这里是一个示例代码,用于绘制混合流水车间调度问题的甘特图。这个代码使用了Python的matplotlib库来绘制图表。
```python
import matplotlib.pyplot as plt
import numpy as np
# 任务列表
TASKS = [
(1, 2, 3, 4),
(2, 1, 4, 3),
(3, 4, 1, 2),
(4, 3, 2, 1),
(1, 2, 3, 4),
(2, 1, 4, 3),
(3, 4, 1, 2),
(4, 3, 2, 1),
(1, 2, 3, 4),
(2, 1, 4, 3),
(3, 4, 1, 2),
(4, 3, 2, 1),
]
# 机器列表
MACHINES = ['M1', 'M2', 'M3', 'M4']
# 甘特图的时间单位
TIME_UNIT = 1
# 计算每个任务在每个机器上的开始和结束时间
start_times = []
end_times = []
for task in TASKS:
task_start_times = []
task_end_times = []
for i, machine in enumerate(MACHINES):
if i == 0:
task_start_times.append(0)
task_end_times.append(TIME_UNIT * task[i])
else:
task_start_times.append(task_end_times[i-1])
task_end_times.append(task_start_times[i] + TIME_UNIT * task[i])
start_times.append(task_start_times)
end_times.append(task_end_times)
# 绘制甘特图
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制每个任务的条形
for i, task in enumerate(TASKS):
for j, machine in enumerate(MACHINES):
start_time = start_times[i][j]
end_time = end_times[i][j]
duration = end_time - start_time
ax.barh(i, duration, left=start_time, height=0.5, color='C{}'.format(j), alpha=0.8)
ax.text(start_time + duration / 2, i + 0.25, '{}'.format(machine), ha='center', va='center')
# 设置坐标轴标签
ax.set_xlabel('Time')
ax.set_ylabel('Task')
# 设置坐标轴范围
ax.set_xlim(0, max(end_times[-1]))
ax.set_ylim(-0.5, len(TASKS) - 0.5)
# 设置y轴标签
ax.set_yticks(np.arange(len(TASKS)))
ax.set_yticklabels(['T{}'.format(i+1) for i in range(len(TASKS))])
# 设置x轴标签
xticks = np.arange(0, max(end_times[-1])+1, 5)
ax.set_xticks(xticks)
ax.set_xticklabels(['{}:00'.format(i) for i in xticks])
# 添加图例
handles = [plt.Rectangle((0, 0), 1, 1, color='C{}'.format(i), alpha=0.8) for i in range(len(MACHINES))]
ax.legend(handles, MACHINES, loc='upper right')
# 显示图表
plt.show()
```
这段代码可以生成类似下面的甘特图:
![Gantt Chart](https://i.imgur.com/0txjKxO.png)
阅读全文