基于rectpack的2D装箱问题:尺寸/数量异常及箱号输出需求
装箱问题与优化需求
我有一批包含ID、长度、宽度、数量的物品数据,需要装入统一尺寸的容器。使用rectpack库实现装箱可视化后,遇到两个问题:
- 部分物品尺寸无法匹配容器
- 实际放置的物品数量超出需求
另外,需要在原数据的第五列添加每个物品ID对应的装箱容器编号。
原实现代码
import pandas as pd import matplotlib.pyplot as plt from rectpack import newPacker # 加载Excel文件数据 file_path = "/content/drive/MyDrive/Colab Notebooks/Transport/module dimensions.xlsx" df = pd.read_excel(file_path) # 检测列名 item_identity_column = df.columns[0] width_column = df.columns[1] height_column = df.columns[2] amount_column = df.columns[3] # 从DataFrame提取宽、高和数量 rectangles = [(row[width_column], row[height_column], row[amount_column]) for _, row in df.iterrows()] # 初始化装箱器 packer = newPacker() # 设置容器尺寸 bin_width, bin_height = 81, 22 # 将物品装入容器 current_bin = 0 while rectangles: # 添加新容器 packer.add_bin(bin_width, bin_height) # 向装箱器添加物品 for i, (width, height, amount) in enumerate(rectangles): for _ in range(amount): packer.add_rect(width, height, rid=i) # 执行装箱 packer.pack() # 获取当前容器已装入的物品 packed_rectangles = packer[current_bin] # 从待装箱列表中移除已装入的物品类型 rectangles = [rect for i, rect in enumerate(rectangles) if i not in set(r.rid for r in packed_rectangles)] # 绘制当前容器的物品放置图并标注中心 fig, ax = plt.subplots() for rect in packed_rectangles: x, y, w, h = rect.x, rect.y, rect.width, rect.height ax.add_patch(plt.Rectangle((x, y), w, h, linewidth=1, edgecolor='b', facecolor='none')) ax.text(x + w / 2, y + h / 2, f"#{rect.rid + 1}", ha='center', va='center', color='r') # 绘制中心间距≤1单位的物品连线 for other_rect in packed_rectangles: if rect != other_rect: other_x, other_y = other_rect.x + other_rect.width / 2, other_rect.y + other_rect.height / 2 distance = ((x + w / 2 - other_x) ** 2 + (y + h / 2 - other_y) ** 2) ** 0.5 if distance <= 1: ax.plot([x + w / 2, other_x], [y + h / 2, other_y], color='gray', linestyle='--') # 设置坐标轴刻度(每5单位) ax.set_xticks(range(0, bin_width + 1, 5)) ax.set_yticks(range(0, bin_height + 1, 5)) ax.grid(True, linestyle='--', linewidth=0.5) # 设置坐标轴范围 ax.set_xlim(0, bin_width) ax.set_ylim(0, bin_height) # 设置坐标轴等比例显示 ax.set_aspect('equal') # 设置坐标轴标签 ax.set_xlabel('长度') ax.set_ylabel('宽度') # 设置图表标题 ax.set_title(f'容器 #{current_bin + 1} 物品放置图') # 显示图表 plt.show() # 切换到下一个容器 current_bin += 1
物品数据
ID a b amount 1 15 18 1 2 12 28 6 3 5 14 3 4 12 15 1 5 6 11 2 6 7 18 4 7 8 42 3 8 3 36 3 9 5 5 12 10 4 7 6 11 4 12 22 12 4 3 44 13 4 26 1 14 12 37 3 15 5 12 1 16 6 18 11 17 3 12 32 18 3 3 47 19 15 24 4 20 18 37 3 21 14 40 4 22 16 33 1 23 10 35 1 24 12 47 3 25 11 42 2 26 5 3 14 27 5 42 1 28 5 19 1 29 2 3 5 30 2 12 1 31 6 40 1 32 6 30 3 33 6 24 3 34 4 13 1 35 14 24 2 36 18 26 1 37 13 39 2 38 16 40 2 39 10 42 1 40 4 6 18 41 4 20 1 42 2 16 3 43 6 42 2 44 6 20 2 45 14 30 2 46 11 45 3 47 5 22 1 48 6 23 1
内容的提问来源于stack exchange,提问作者ANG BN
相关产品推荐
相关产品推荐

