启发式产线分配

This commit is contained in:
2023-07-16 23:19:34 +08:00
parent 6e56f796f0
commit 96430a4b6c
11 changed files with 439 additions and 200 deletions

View File

@ -1,15 +1,18 @@
from base_optimizer.optimizer_common import * from base_optimizer.optimizer_common import *
from ortools.sat.python import cp_model from gurobipy import *
from collections import defaultdict from collections import defaultdict
def list_range(start, end=None):
return list(range(start)) if end is None else list(range(start, end))
@timer_wrapper @timer_wrapper
def optimizer_aggregation(component_data, pcb_data): def optimizer_aggregation(component_data, pcb_data):
# === phase 0: data preparation === # === phase 0: data preparation ===
M = 1000 # a sufficient large number M = 1000 # a sufficient large number
a, b = 1, 6 # coefficient a, b = 1, 6 # coefficient
K, I, J, L = max_head_index, 0, 0, 0 # the maximum number of heads, component types, nozzle types and batch level
component_list, nozzle_list = defaultdict(int), defaultdict(int) component_list, nozzle_list = defaultdict(int), defaultdict(int)
cpidx_2_part, nzidx_2_nozzle = {}, {} cpidx_2_part, nzidx_2_nozzle = {}, {}
@ -26,10 +29,11 @@ def optimizer_aggregation(component_data, pcb_data):
nzidx_2_nozzle[len(nzidx_2_nozzle)] = nozzle nzidx_2_nozzle[len(nzidx_2_nozzle)] = nozzle
nozzle_list[nozzle] += 1 nozzle_list[nozzle] += 1
I, J = len(component_list.keys()), len(nozzle_list.keys()) I, J = len(component_list.keys()), len(nozzle_list.keys()) # the maximum number of component types and nozzle types
L = I + 1 L = I + 1 # the maximum number of batch level
HC = [[M for _ in range(J)] for _ in range(I)] # the handing class when component i is handled by nozzle type j K = max_head_index # the maximum number of heads
# represent the nozzle-component compatibility HC = [[M for _ in range(J)] for _ in range(I)] # represent the nozzle-component compatibility
for i in range(I): for i in range(I):
for _, item in enumerate(cpidx_2_part.items()): for _, item in enumerate(cpidx_2_part.items()):
index, part = item index, part = item
@ -41,105 +45,71 @@ def optimizer_aggregation(component_data, pcb_data):
HC[index][j] = 0 HC[index][j] = 0
# === phase 1: mathematical model solver === # === phase 1: mathematical model solver ===
model = cp_model.CpModel() mdl = Model('SMT')
solver = cp_model.CpSolver() mdl.setParam('OutputFlag', 0)
# === Decision Variables === # === Decision Variables ===
# the number of components of type i that are placed by nozzle type j on placement head k # the number of components of type i that are placed by nozzle type j on placement head k
X = {} X = mdl.addVars(list_range(I), list_range(J), list_range(K), vtype=GRB.INTEGER, ub=max(component_list.values()))
for i in range(I):
for j in range(J):
for k in range(K):
X[i, j, k] = model.NewIntVar(0, component_list[cpidx_2_part[i]], 'X_{}_{}_{}'.format(i, j, k))
# the total number of nozzle changes on placement head k # the total number of nozzle changes on placement head k
N = {} N = mdl.addVars(list_range(K), vtype=GRB.INTEGER)
for k in range(K):
N[k] = model.NewIntVar(0, J, 'N_{}'.format(k))
# the largest workload of all placement heads # the largest workload of all placement heads
WL = model.NewIntVar(0, len(pcb_data), 'WL') WL = mdl.addVar(vtype=GRB.INTEGER, lb=0, ub=len(pcb_data))
# whether batch Xijk is placed on level l # whether batch Xijk is placed on level l
Z = {} Z = mdl.addVars(list_range(I), list_range(J), list_range(L), list_range(K), vtype=GRB.BINARY)
for i in range(I):
for j in range(J):
for l in range(L):
for k in range(K):
Z[i, j, l, k] = model.NewBoolVar('Z_{}_{}_{}_{}'.format(i, j, l, k))
# Dlk := 2 if a change of nozzles in the level l + 1 on placement head k # Dlk := 2 if a change of nozzles in the level l + 1 on placement head k
# Dlk := 1 if there are no batches placed on levels higher than l # Dlk := 1 if there are no batches placed on levels higher than l
D = {} # Dlk := 0 otherwise
for l in range(L): D = mdl.addVars(list_range(L), list_range(K), vtype=GRB.BINARY, ub=2)
for k in range(K): D_plus = mdl.addVars(list_range(L), list_range(J), list_range(K), vtype=GRB.INTEGER)
D[l, k] = model.NewIntVar(0, 2, 'D_{}_{}'.format(l, k)) D_minus = mdl.addVars(list_range(L), list_range(J), list_range(K), vtype=GRB.INTEGER)
D_abs = {}
for l in range(L):
for j in range(J):
for k in range(K):
D_abs[l, j, k] = model.NewIntVar(0, M, 'D_abs_{}_{}_{}'.format(l, j, k))
# == Objective function === # == Objective function ===
model.Minimize(a * WL + b * sum(N[k] for k in range(K))) mdl.modelSense = GRB.MINIMIZE
mdl.setObjective(a * WL + b * quicksum(N[k] for k in range(K)))
# === Constraint === # === Constraint ===
for i in range(I): mdl.addConstrs(
model.Add(sum(X[i, j, k] for j in range(J) for k in range(K)) == component_list[cpidx_2_part[i]]) quicksum(X[i, j, k] for j in range(J) for k in range(K)) == component_list[cpidx_2_part[i]] for i in range(I))
for k in range(K): mdl.addConstrs(quicksum(X[i, j, k] for i in range(I) for j in range(J)) <= WL for k in range(K))
model.Add(sum(X[i, j, k] for i in range(I) for j in range(J)) <= WL)
for i in range(I): mdl.addConstrs(
for j in range(J): X[i, j, k] <= M * quicksum(Z[i, j, l, k] for l in range(L)) for i in range(I) for j in range(J) for k in
for k in range(K): range(K))
model.Add(X[i, j, k] <= M * sum(Z[i, j, l, k] for l in range(L)))
for i in range(I): mdl.addConstrs(quicksum(Z[i, j, l, k] for l in range(L)) <= 1 for i in range(I) for j in range(J) for k in range(K))
for j in range(J): mdl.addConstrs(
for k in range(K): quicksum(Z[i, j, l, k] for l in range(L)) <= X[i, j, k] for i in range(I) for j in range(J) for k in range(K))
model.Add(sum(Z[i, j, l, k] for l in range(L)) <= 1)
for i in range(I): mdl.addConstrs(quicksum(Z[i, j, l, k] for j in range(J) for i in range(I)) >= quicksum(
for j in range(J): Z[i, j, l + 1, k] for j in range(J) for i in range(I)) for k in range(K) for l in range(L - 1))
for k in range(K):
model.Add(sum(Z[i, j, l, k] for l in range(L)) <= X[i, j, k])
for k in range(K): mdl.addConstrs(quicksum(Z[i, j, l, k] for i in range(I) for j in range(J)) <= 1 for k in range(K) for l in range(L))
for l in range(L - 1): mdl.addConstrs(D_plus[l, j, k] - D_minus[l, j, k] == quicksum(Z[i, j, l, k] for i in range(I)) - quicksum(
model.Add(sum(Z[i, j, l, k] for j in range(J) for i in range(I)) >= sum( Z[i, j, l + 1, k] for i in range(I)) for l in range(L - 1) for j in range(J) for k in range(K))
Z[i, j, l + 1, k] for j in range(J) for i in range(I)))
for l in range(I): mdl.addConstrs(
for k in range(K): D[l, k] == quicksum((D_plus[l, j, k] + D_minus[l, j, k]) for j in range(J)) for k in range(K) for l in
model.Add(sum(Z[i, j, l, k] for i in range(I) for j in range(J)) <= 1) range(L))
for l in range(L - 1): mdl.addConstrs(2 * N[k] == quicksum(D[l, k] for l in range(L)) - 1 for k in range(K))
for j in range(J): mdl.addConstrs(
for k in range(K): 0 >= quicksum(HC[i][j] * Z[i, j, l, k] for i in range(I) for j in range(J)) for l in range(L) for k in range(K))
model.AddAbsEquality(D_abs[l, j, k],
sum(Z[i, j, l, k] for i in range(I)) - sum(Z[i, j, l + 1, k] for i in range(I)))
for k in range(K):
for l in range(L):
model.Add(D[l, k] == sum(D_abs[l, j, k] for j in range(J)))
for k in range(K):
model.Add(N[k] == sum(D[l, k] for l in range(L)) - 1)
for l in range(L):
for k in range(K):
model.Add(0 >= sum(HC[i][j] * Z[i, j, l, k] for i in range(I) for j in range(J)))
# === Main Process === # === Main Process ===
component_result, cycle_result = [], [] component_result, cycle_result = [], []
feeder_slot_result, placement_result, head_sequence = [], [], [] feeder_slot_result, placement_result, head_sequence = [], [], []
solver.parameters.max_time_in_seconds = 20.0 mdl.setParam("TimeLimit", 100)
status = solver.Solve(model) mdl.optimize()
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
print('total cost = {}'.format(solver.ObjectiveValue())) if mdl.Status == GRB.OPTIMAL:
print('total cost = {}'.format(mdl.objval))
# convert cp model solution to standard output # convert cp model solution to standard output
model_cycle_result, model_component_result = [], [] model_cycle_result, model_component_result = [], []
@ -149,9 +119,9 @@ def optimizer_aggregation(component_data, pcb_data):
for k in range(K): for k in range(K):
for i in range(I): for i in range(I):
for j in range(J): for j in range(J):
if solver.BooleanValue(Z[i, j, l, k]) != 0: if abs(Z[i, j, l, k].x - 1) <= 1e-3:
model_component_result[-1][k] = cpidx_2_part[i] model_component_result[-1][k] = cpidx_2_part[i]
model_cycle_result[-1][k] = solver.Value(X[i, j, k]) model_cycle_result[-1][k] = round(X[i, j, k].x)
# remove redundant term # remove redundant term
if sum(model_cycle_result[-1]) == 0: if sum(model_cycle_result[-1]) == 0:
@ -209,7 +179,6 @@ def optimizer_aggregation(component_data, pcb_data):
if component_result[cycle_idx][head] == -1: if component_result[cycle_idx][head] == -1:
continue continue
index_ = component_result[cycle_idx][head] index_ = component_result[cycle_idx][head]
placement_result[-1][head] = mount_point_pos[index_][-1][2] placement_result[-1][head] = mount_point_pos[index_][-1][2]
mount_point_pos[index_].pop() mount_point_pos[index_].pop()
head_sequence.append(dynamic_programming_cycle_path(pcb_data, placement_result[-1], feeder_slot_result[cycle_idx])) head_sequence.append(dynamic_programming_cycle_path(pcb_data, placement_result[-1], feeder_slot_result[cycle_idx]))

View File

@ -49,6 +49,12 @@ feeder_width = {'SM8': (7.25, 7.25), 'SM12': (7.00, 20.00), 'SM16': (7.00, 22.00
# 可用吸嘴数量限制 # 可用吸嘴数量限制
nozzle_limit = {'CN065': 6, 'CN040': 6, 'CN220': 6, 'CN400': 6, 'CN140': 6} nozzle_limit = {'CN065': 6, 'CN040': 6, 'CN220': 6, 'CN400': 6, 'CN140': 6}
# 时间参数
t_cycle = 0.3
t_pick, t_place = .078, .051 # 贴装/拾取用时
t_nozzle_put, t_nozzle_pick = 0.9, 0.75 # 装卸吸嘴用时
t_nozzle_change = t_nozzle_put + t_nozzle_pick
t_fix_camera_check = 0.12 # 固定相机检测时间
def axis_moving_time(distance, axis=0): def axis_moving_time(distance, axis=0):
distance = abs(distance) * 1e-3 distance = abs(distance) * 1e-3
@ -880,7 +886,7 @@ def constraint_swap_mutation(component_points, individual):
offspring = individual.copy() offspring = individual.copy()
idx, component_index = 0, random.randint(0, len(component_points) - 1) idx, component_index = 0, random.randint(0, len(component_points) - 1)
for points in component_points.values(): for _, points in component_points:
if component_index == 0: if component_index == 0:
while True: while True:
index1, index2 = random.sample(range(points + max_machine_index - 2), 2) index1, index2 = random.sample(range(points + max_machine_index - 2), 2)

View File

@ -2,7 +2,7 @@ from base_optimizer.optimizer_common import *
@timer_wrapper @timer_wrapper
def feeder_allocate(component_data, pcb_data, feeder_data, nozzle_pattern, figure=False): def feeder_allocate(component_data, pcb_data, feeder_data, figure=False):
feeder_points, feeder_division_points = defaultdict(int), defaultdict(int) # 供料器贴装点数 feeder_points, feeder_division_points = defaultdict(int), defaultdict(int) # 供料器贴装点数
mount_center_pos = defaultdict(int) mount_center_pos = defaultdict(int)

View File

@ -234,8 +234,8 @@ def cal_individual_val(component_nozzle, component_point_pos, designated_nozzle,
return V[-1], pickup_result, pickup_cycle_result return V[-1], pickup_result, pickup_cycle_result
def convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group, pickup_group_cycle, def convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group,
pair_group, feeder_lane, individual): pickup_group_cycle, pair_group, feeder_lane, individual):
component_result, cycle_result, feeder_slot_result = [], [], [] component_result, cycle_result, feeder_slot_result = [], [], []
placement_result, head_sequence_result = [], [] placement_result, head_sequence_result = [], []
@ -418,19 +418,19 @@ def optimizer_hybrid_genetic(pcb_data, component_data, hinter=True):
pick_part = pickup[pickup_index] pick_part = pickup[pickup_index]
# 检查槽位占用情况 # 检查槽位占用情况
if feeder_lane[slot] is not None and pick_part is not None: if feeder_lane[slot] and pick_part:
assign_available = False assign_available = False
break break
# 检查机械限位冲突 # 检查机械限位冲突
if pick_part is not None and (slot - CT_Head[pick_part][0] * interval_ratio <= 0 or if pick_part and (slot - CT_Head[pick_part][0] * interval_ratio <= 0 or slot + (
slot + (max_head_index - CT_Head[pick_part][1] - 1) * interval_ratio > max_slot_index // 2): max_head_index - CT_Head[pick_part][1] - 1) * interval_ratio > max_slot_index // 2):
assign_available = False assign_available = False
break break
if assign_available: if assign_available:
for idx, component in enumerate(pickup): for idx, component in enumerate(pickup):
if component is not None: if component:
feeder_lane[assign_slot + idx * interval_ratio] = component feeder_lane[assign_slot + idx * interval_ratio] = component
CT_Group_slot[CTIdx] = assign_slot CT_Group_slot[CTIdx] = assign_slot
break break
@ -509,32 +509,31 @@ def optimizer_hybrid_genetic(pcb_data, component_data, hinter=True):
with tqdm(total=n_generations) as pbar: with tqdm(total=n_generations) as pbar:
pbar.set_description('hybrid genetic process') pbar.set_description('hybrid genetic process')
# calculate fitness value
pop_val = []
for pop_idx, individual in enumerate(population):
val, _, _ = cal_individual_val(component_nozzle, component_point_pos, designated_nozzle, pickup_group,
pickup_group_cycle, pair_group, feeder_part_arrange, individual)
pop_val.append(val) # val is related to assembly time
for _ in range(n_generations): for _ in range(n_generations):
# calculate fitness value # idx = np.argmin(pop_val)
pop_val = [] # if len(best_pop_val) == 0 or pop_val[idx] < best_pop_val[-1]:
for pop_idx, individual in enumerate(population): # best_individual = copy.deepcopy(population[idx])
val, _, _ = cal_individual_val(component_nozzle, component_point_pos, designated_nozzle, pickup_group, # best_pop_val.append(pop_val[idx])
pickup_group_cycle, pair_group, feeder_part_arrange, individual)
pop_val.append(val)
idx = np.argmin(pop_val)
if len(best_pop_val) == 0 or pop_val[idx] < best_pop_val[-1]:
best_individual = copy.deepcopy(population[idx])
best_pop_val.append(pop_val[idx])
# min-max convert # min-max convert
max_val = 1.5 * max(pop_val) max_val = 1.5 * max(pop_val)
pop_val = list(map(lambda v: max_val - v, pop_val)) convert_pop_val = list(map(lambda v: max_val - v, pop_val))
# crossover and mutation # crossover and mutation
c = 0 c = 0
new_population = [] new_population, new_pop_val = [], []
for pop in range(population_size): for pop in range(population_size):
if pop % 2 == 0 and np.random.random() < crossover_rate: if pop % 2 == 0 and np.random.random() < crossover_rate:
index1, index2 = roulette_wheel_selection(pop_val), -1 index1, index2 = roulette_wheel_selection(convert_pop_val), -1
while True: while True:
index2 = roulette_wheel_selection(pop_val) index2 = roulette_wheel_selection(convert_pop_val)
if index1 != index2: if index1 != index2:
break break
# 两点交叉算子 # 两点交叉算子
@ -552,13 +551,27 @@ def optimizer_hybrid_genetic(pcb_data, component_data, hinter=True):
new_population.append(offspring1) new_population.append(offspring1)
new_population.append(offspring2) new_population.append(offspring2)
# selection val, _, _ = cal_individual_val(component_nozzle, component_point_pos, designated_nozzle,
top_k_index = get_top_k_value(pop_val, population_size - len(new_population)) pickup_group,
pickup_group_cycle, pair_group, feeder_part_arrange, offspring1)
new_pop_val.append(val)
val, _, _ = cal_individual_val(component_nozzle, component_point_pos, designated_nozzle,
pickup_group,
pickup_group_cycle, pair_group, feeder_part_arrange, offspring2)
new_pop_val.append(val)
# generate next generation
top_k_index = get_top_k_value(pop_val, population_size - len(new_population), reverse=False)
for index in top_k_index: for index in top_k_index:
new_population.append(population[index]) new_population.append(population[index])
new_pop_val.append(pop_val[index])
population = new_population population = new_population
pop_val = new_pop_val
pbar.update(1) pbar.update(1)
best_individual = population[np.argmin(pop_val)]
return convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group, return convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group,
pickup_group_cycle, pair_group, feeder_lane, best_individual) pickup_group_cycle, pair_group, feeder_lane, best_individual)

View File

@ -3,11 +3,11 @@ from base_optimizer.optimizer_common import *
@timer_wrapper @timer_wrapper
def optimizer_scanbased(component_data, pcb_data, hinter): def optimizer_genetic_scanning(component_data, pcb_data, hinter):
population_size = 200 # 种群规模 population_size = 200 # 种群规模
crossover_rate, mutation_rate = .4, .02 crossover_rate, mutation_rate = .4, .02
n_generation = 5 n_generation = 500
component_points = [0] * len(component_data) component_points = [0] * len(component_data)
for i in range(len(pcb_data)): for i in range(len(pcb_data)):
@ -31,49 +31,51 @@ def optimizer_scanbased(component_data, pcb_data, hinter):
pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result))
# todo: 过程写的有问题,暂时不想改 sigma_scaling(pop_val, 1)
with tqdm(total=n_generation) as pbar: with tqdm(total=n_generation) as pbar:
pbar.set_description('hybrid genetic process') pbar.set_description('hybrid genetic process')
new_pop_val, new_pop_individual = [], []
# min-max convert
max_val = 1.5 * max(pop_val)
convert_pop_val = list(map(lambda v: max_val - v, pop_val))
for _ in range(n_generation): for _ in range(n_generation):
# 交叉 # 交叉
for pop in range(population_size): for pop in range(population_size):
if pop % 2 == 0 and np.random.random() < crossover_rate: if pop % 2 == 0 and np.random.random() < crossover_rate:
index1, index2 = roulette_wheel_selection(pop_val), -1 index1, index2 = roulette_wheel_selection(convert_pop_val), -1
while True: while True:
index2 = roulette_wheel_selection(pop_val) index2 = roulette_wheel_selection(convert_pop_val)
if index1 != index2: if index1 != index2:
break break
# 两点交叉算子 # 两点交叉算子
offspring1, offspring2 = cycle_crossover(pop_individual[index1], pop_individual[index2]) offspring1, offspring2 = cycle_crossover(pop_individual[index1], pop_individual[index2])
# 变异
if np.random.random() < mutation_rate:
offspring1 = swap_mutation(offspring1)
if np.random.random() < mutation_rate:
offspring2 = swap_mutation(offspring2)
_, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring1) _, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring1)
pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) new_pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result))
pop_individual.append(offspring1) new_pop_individual.append(offspring1)
_, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring2) _, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring2)
pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) new_pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result))
pop_individual.append(offspring2) new_pop_individual.append(offspring2)
sigma_scaling(pop_val, 1) # generate next generation
top_k_index = get_top_k_value(pop_val, population_size - len(new_pop_individual), reverse=False)
for index in top_k_index:
new_pop_individual.append(pop_individual[index])
new_pop_val.append(pop_val[index])
# 变异 pop_individual, pop_val = new_pop_individual, new_pop_val
if np.random.random() < mutation_rate: sigma_scaling(pop_val, 1)
index_ = roulette_wheel_selection(pop_val)
offspring = swap_mutation(pop_individual[index_])
_, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring)
pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result))
pop_individual.append(offspring)
sigma_scaling(pop_val, 1)
new_population, new_popval = [], []
for index in get_top_k_value(pop_val, population_size):
new_population.append(pop_individual[index])
new_popval.append(pop_val[index])
pop_individual, pop_val = new_population, new_popval
# select the best individual # select the best individual
pop = np.argmin(pop_val) pop = np.argmin(pop_val)
@ -98,7 +100,6 @@ def convert_individual_2_result(component_points, pop):
feeder_part[gene], feeder_base_points[gene] = idx, component_points[idx] feeder_part[gene], feeder_base_points[gene] = idx, component_points[idx]
# TODO: 暂时未考虑可用吸嘴数的限制 # TODO: 暂时未考虑可用吸嘴数的限制
# for _ in range(math.ceil(sum(component_points) / max_head_index)):
while True: while True:
# === 周期内循环 === # === 周期内循环 ===
assigned_part = [-1 for _ in range(max_head_index)] # 当前扫描到的头分配元件信息 assigned_part = [-1 for _ in range(max_head_index)] # 当前扫描到的头分配元件信息

View File

@ -27,7 +27,7 @@ def load_data(filename: str, default_feeder_limit=1, load_cp_data=True, load_fee
# 注册元件检查 # 注册元件检查
part_feeder_assign = defaultdict(set) part_feeder_assign = defaultdict(set)
part_col = ["part", "desc", "fdr", "nz", 'camera', 'group', 'feeder-limit'] part_col = ["part", "desc", "fdr", "nz", 'camera', 'group', 'feeder-limit', 'points']
try: try:
if load_cp_data: if load_cp_data:
component_data = pd.DataFrame(pd.read_csv(filepath_or_buffer='component.txt', sep='\t', header=None), component_data = pd.DataFrame(pd.read_csv(filepath_or_buffer='component.txt', sep='\t', header=None),
@ -40,18 +40,18 @@ def load_data(filename: str, default_feeder_limit=1, load_cp_data=True, load_fee
for _, data in pcb_data.iterrows(): for _, data in pcb_data.iterrows():
part, nozzle = data.part, data.nz.split(' ')[1] part, nozzle = data.part, data.nz.split(' ')[1]
slot = data['fdr'].split(' ')[0] slot = data['fdr'].split(' ')[0]
if part not in component_data['part'].values: if part not in component_data['part'].values:
if not cp_auto_register: if not cp_auto_register:
raise Exception("unregistered component: " + component_data['part'].values) raise Exception("unregistered component: " + component_data['part'].values)
else: else:
component_data = pd.concat([component_data, pd.DataFrame( component_data = pd.concat([component_data, pd.DataFrame(
[part, '', 'SM8', nozzle, '飞行相机1', 'CHIP-Rect', default_feeder_limit], index=part_col).T], [part, '', 'SM8', nozzle, '飞行相机1', 'CHIP-Rect', default_feeder_limit, 0], index=part_col).T],
ignore_index=True) ignore_index=True)
# warning_info = 'register component ' + part + ' with default feeder type' # warning_info = 'register component ' + part + ' with default feeder type'
# warnings.warn(warning_info, UserWarning) # warnings.warn(warning_info, UserWarning)
part_index = component_data[component_data['part'] == part].index.tolist()[0] part_index = component_data[component_data['part'] == part].index.tolist()[0]
part_feeder_assign[part].add(slot) part_feeder_assign[part].add(slot)
component_data.loc[part_index]['points'] += 1
if nozzle != 'A' and component_data.loc[part_index]['nz'] != nozzle: if nozzle != 'A' and component_data.loc[part_index]['nz'] != nozzle:
warning_info = 'the nozzle type of component ' + part + ' is not consistent with the pcb data' warning_info = 'the nozzle type of component ' + part + ' is not consistent with the pcb data'
@ -64,9 +64,8 @@ def load_data(filename: str, default_feeder_limit=1, load_cp_data=True, load_fee
# 读取供料器基座数据 # 读取供料器基座数据
feeder_data = pd.DataFrame(columns=['slot', 'part', 'arg']) # arg表示是否为预分配不表示分配数目 feeder_data = pd.DataFrame(columns=['slot', 'part', 'arg']) # arg表示是否为预分配不表示分配数目
if load_feeder_data: if load_feeder_data:
for data in pcb_data.iterrows(): for _, data in pcb_data.iterrows():
fdr = data[1]['fdr'] slot, part = data['fdr'].split(' ')
slot, part = fdr.split(' ')
if slot[0] != 'F' and slot[0] != 'R': if slot[0] != 'F' and slot[0] != 'R':
continue continue
slot = int(slot[1:]) if slot[0] == 'F' else int(slot[1:]) + max_slot_index // 2 slot = int(slot[1:]) if slot[0] == 'F' else int(slot[1:]) + max_slot_index // 2
@ -80,6 +79,5 @@ def load_data(filename: str, default_feeder_limit=1, load_cp_data=True, load_fee
feeder_data.sort_values(by='slot', ascending=True, inplace=True, ignore_index=True) feeder_data.sort_values(by='slot', ascending=True, inplace=True, ignore_index=True)
# plt.scatter(pcb_data["x"], pcb_data["y"]) pcb_data = pcb_data.sort_values(by="x", ascending=False)
# plt.show()
return pcb_data, component_data, feeder_data return pcb_data, component_data, feeder_data

View File

@ -1,3 +1,4 @@
import copy
import math import math
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -15,10 +16,21 @@ from optimizer_genetic import *
from optimizer_heuristic import * from optimizer_heuristic import *
def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_optimizer): def deviation(data):
assignment_result = assemblyline_optimizer_genetic(pcb_data, component_data) assert len(data) > 0
average, variance = sum(data) / len(data), 0
for v in data:
variance += (v - average) ** 2
return variance / len(data)
# assignment_result = [[0, 0, 0, 0, 216, 0, 0], [0, 0, 0, 0, 216, 0, 0], [36, 24, 12, 12, 0, 36, 12]]
def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_optimizer):
# todo: 由于吸嘴更换更因素的存在在处理PCB8数据时遗传算法因在负载均衡过程中对这一因素进行了考虑性能更优
assignment_result = assemblyline_optimizer_heuristic(pcb_data, component_data)
# assignment_result = assemblyline_optimizer_genetic(pcb_data, component_data)
print(assignment_result)
assignment_result_cpy = copy.deepcopy(assignment_result)
placement_points, placement_time = [], [] placement_points, placement_time = [], []
partial_pcb_data, partial_component_data = defaultdict(pd.DataFrame), defaultdict(pd.DataFrame) partial_pcb_data, partial_component_data = defaultdict(pd.DataFrame), defaultdict(pd.DataFrame)
for machine_index in range(max_machine_index): for machine_index in range(max_machine_index):
@ -26,7 +38,9 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_
partial_component_data[machine_index] = component_data.copy(deep=True) partial_component_data[machine_index] = component_data.copy(deep=True)
placement_points.append(sum(assignment_result[machine_index])) placement_points.append(sum(assignment_result[machine_index]))
# averagely assign available feeder assert sum(placement_points) == len(pcb_data)
# === averagely assign available feeder ===
for part_index, data in component_data.iterrows(): for part_index, data in component_data.iterrows():
feeder_limit = data['feeder-limit'] feeder_limit = data['feeder-limit']
feeder_points = [assignment_result[machine_index][part_index] for machine_index in range(max_machine_index)] feeder_points = [assignment_result[machine_index][part_index] for machine_index in range(max_machine_index)]
@ -49,11 +63,14 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_
partial_component_data[machine_index].loc[part_index]['feeder-limit'] += 1 partial_component_data[machine_index].loc[part_index]['feeder-limit'] += 1
feeder_limit -= 1 feeder_limit -= 1
for machine_index in range(max_machine_index):
if feeder_points[machine_index] > 0:
assert partial_component_data[machine_index].loc[part_index]['feeder-limit'] > 0
# === assign placements ===
component_machine_index = [0 for _ in range(len(component_data))] component_machine_index = [0 for _ in range(len(component_data))]
pcb_data = pcb_data.sort_values(by="x", ascending=False)
for _, data in pcb_data.iterrows(): for _, data in pcb_data.iterrows():
part = data['part'] part_index = component_data[component_data['part'] == data['part']].index.tolist()[0]
part_index = component_data[component_data['part'] == part].index.tolist()[0]
while True: while True:
machine_index = component_machine_index[part_index] machine_index = component_machine_index[part_index]
if assignment_result[machine_index][part_index] == 0: if assignment_result[machine_index][part_index] == 0:
@ -64,11 +81,60 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_
assignment_result[machine_index][part_index] -= 1 assignment_result[machine_index][part_index] -= 1
partial_pcb_data[machine_index] = pd.concat([partial_pcb_data[machine_index], pd.DataFrame(data).T]) partial_pcb_data[machine_index] = pd.concat([partial_pcb_data[machine_index], pd.DataFrame(data).T])
# === adjust the number of available feeders for single optimization separately ===
for machine_index, data in partial_pcb_data.items(): for machine_index, data in partial_pcb_data.items():
data = data.reset_index(drop=True) data = data.reset_index(drop=True)
if len(data) == 0: if len(data) == 0:
continue continue
part_info = [] # part info list(part index, part points, available feeder-num, upper feeder-num)
for part_index, cp_data in partial_component_data[machine_index].iterrows():
if assignment_result_cpy[machine_index][part_index]:
part_info.append(
[part_index, assignment_result_cpy[machine_index][part_index], 1, cp_data['feeder-limit']])
part_info = sorted(part_info, key=lambda x: x[1], reverse=True)
start_index, end_index = 0, min(max_head_index - 1, len(part_info) - 1)
while start_index < len(part_info):
assign_part_point, assign_part_index = [], []
for idx_ in range(start_index, end_index + 1):
for _ in range(part_info[idx_][2]):
assign_part_point.append(part_info[idx_][1] / part_info[idx_][2])
assign_part_index.append(idx_)
variance = deviation(assign_part_point)
while start_index != end_index:
part_info_index = assign_part_index[np.argmax(assign_part_point)]
if part_info[part_info_index][2] < part_info[part_info_index][3]: # 供料器数目上限的限制
part_info[part_info_index][2] += 1
end_index -= 1
new_assign_part_point, new_assign_part_index = [], []
for idx_ in range(start_index, end_index + 1):
for _ in range(part_info[idx_][2]):
new_assign_part_point.append(part_info[idx_][1] / part_info[idx_][2])
new_assign_part_index.append(idx_)
new_variance = deviation(new_assign_part_point)
if variance < new_variance:
part_info[part_info_index][2] -= 1
end_index += 1
break
variance = new_variance
assign_part_index, assign_part_point = new_assign_part_index, new_assign_part_point
else:
break
start_index = end_index + 1
end_index = min(start_index + max_head_index - 1, len(part_info) - 1)
# update available feeder number
max_avl_feeder = max(part_info, key=lambda x: x[2])[2]
for info in part_info:
partial_component_data[machine_index].loc[info[0]]['feeder-limit'] = math.ceil(info[2] / max_avl_feeder)
placement_time.append(base_optimizer(machine_index + 1, data, partial_component_data[machine_index], placement_time.append(base_optimizer(machine_index + 1, data, partial_component_data[machine_index],
feeder_data=pd.DataFrame(columns=['slot', 'part', 'arg']), feeder_data=pd.DataFrame(columns=['slot', 'part', 'arg']),
method=single_machine_optimizer, hinter=True)) method=single_machine_optimizer, hinter=True))
@ -86,13 +152,15 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_
# todo: 不同类型元件的组装时间差异 # todo: 不同类型元件的组装时间差异
def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, method='', hinter=False): def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, method='', hinter=False):
if method == 'cell_division': # 基于元胞分裂的遗传算法 if method == 'cell_division': # 基于元胞分裂的遗传算法
component_result, cycle_result, feeder_slot_result = optimizer_celldivision(pcb_data, component_data, False) component_result, cycle_result, feeder_slot_result = optimizer_celldivision(pcb_data, component_data,
hinter=False)
placement_result, head_sequence = greedy_placement_route_generation(component_data, pcb_data, component_result, placement_result, head_sequence = greedy_placement_route_generation(component_data, pcb_data, component_result,
cycle_result, feeder_slot_result) cycle_result, feeder_slot_result)
elif method == 'feeder_priority': # 基于基座扫描的供料器优先算法 elif method == 'feeder_scan': # 基于基座扫描的供料器优先算法
# 第1步分配供料器位置 # 第1步分配供料器位置
nozzle_pattern = feeder_allocate(component_data, pcb_data, feeder_data, False) nozzle_pattern = feeder_allocate(component_data, pcb_data, feeder_data, figure=False)
# 第2步扫描供料器基座确定元件拾取的先后顺序 # 第2步扫描供料器基座确定元件拾取的先后顺序
component_result, cycle_result, feeder_slot_result = feeder_base_scan(component_data, pcb_data, feeder_data, component_result, cycle_result, feeder_slot_result = feeder_base_scan(component_data, pcb_data, feeder_data,
nozzle_pattern) nozzle_pattern)
@ -105,25 +173,26 @@ def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, me
elif method == 'hybrid_genetic': # 基于拾取组的混合遗传算法 elif method == 'hybrid_genetic': # 基于拾取组的混合遗传算法
component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_hybrid_genetic( component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_hybrid_genetic(
pcb_data, component_data, False) pcb_data, component_data, hinter=False)
elif method == 'aggregation': # 基于batch-level的整数规划 + 启发式算法 elif method == 'aggregation': # 基于batch-level的整数规划 + 启发式算法
component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_aggregation( component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_aggregation(
component_data, pcb_data) component_data, pcb_data)
elif method == 'scan_based': elif method == 'genetic_scanning':
component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_scanbased( component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_genetic_scanning(
component_data, pcb_data, False) component_data, pcb_data, hinter=False)
else: else:
raise 'method is not existed' raise 'method is not existed'
if hinter: if hinter:
optimization_assign_result(component_data, pcb_data, component_result, cycle_result, feeder_slot_result, optimization_assign_result(component_data, pcb_data, component_result, cycle_result, feeder_slot_result,
nozzle_hinter=False, component_hinter=False, feeder_hinter=False) nozzle_hinter=True, component_hinter=False, feeder_hinter=False)
print('----- Placement machine ' + str(machine_index) + ' ----- ') print('----- Placement machine ' + str(machine_index) + ' ----- ')
print('-Cycle counter: {}'.format(sum(cycle_result))) print('-Cycle counter: {}'.format(sum(cycle_result)))
total_nozzle_change_counter, total_pick_counter = 0, 0 total_nozzle_change_counter, total_pick_counter = 0, 0
total_pick_movement = 0
assigned_nozzle = ['' if idx == -1 else component_data.loc[idx]['nz'] for idx in component_result[0]] assigned_nozzle = ['' if idx == -1 else component_data.loc[idx]['nz'] for idx in component_result[0]]
for cycle in range(len(cycle_result)): for cycle in range(len(cycle_result)):
@ -141,25 +210,31 @@ def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, me
pick_slot.add(feeder_slot_result[cycle][head] - head * interval_ratio) pick_slot.add(feeder_slot_result[cycle][head] - head * interval_ratio)
total_pick_counter += len(pick_slot) * cycle_result[cycle] total_pick_counter += len(pick_slot) * cycle_result[cycle]
pick_slot = list(pick_slot)
pick_slot.sort()
for idx in range(len(pick_slot) - 1):
total_pick_movement += abs(pick_slot[idx+1] - pick_slot[idx])
print('-Nozzle change counter: {}'.format(total_nozzle_change_counter)) print('-Nozzle change counter: {}'.format(total_nozzle_change_counter))
print('-Pick operation counter: {}'.format(total_pick_counter)) print('-Pick operation counter: {}'.format(total_pick_counter))
print('-Pick movement: {}'.format(total_pick_movement))
print('------------------------------ ') print('------------------------------ ')
# 估算贴装用时 # 估算贴装用时
return placement_time_estimate(component_data, pcb_data, component_result, cycle_result, feeder_slot_result, return placement_time_estimate(component_data, pcb_data, component_result, cycle_result, feeder_slot_result,
placement_result, head_sequence, False) placement_result, head_sequence, hinter=False)
@timer_wrapper
def main(): def main():
# warnings.simplefilter('ignore') # warnings.simplefilter('ignore')
# 参数解析 # 参数解析
parser = argparse.ArgumentParser(description='assembly line optimizer implementation') parser = argparse.ArgumentParser(description='assembly line optimizer implementation')
parser.add_argument('--filename', default='PCB1 - FL19-30W.txt', type=str, help='load pcb data') parser.add_argument('--filename', default='PCB.txt', type=str, help='load pcb data')
parser.add_argument('--auto_register', default=1, type=int, help='register the component according the pcb data') parser.add_argument('--auto_register', default=1, type=int, help='register the component according the pcb data')
parser.add_argument('--base_optimizer', default='feeder_priority', type=str, parser.add_argument('--base_optimizer', default='feeder_scan', type=str, help='base optimizer for single machine')
help='base optimizer for single machine') parser.add_argument('--assembly_optimizer', default='heuristic', type=str, help='optimizer for PCB Assembly Line')
parser.add_argument('--assembly_optimizer', default='genetic', type=str, help='optimizer for PCB Assembly Line') parser.add_argument('--feeder_limit', default=3, type=int,
parser.add_argument('--feeder_limit', default=2, type=int,
help='the upper feeder limit for each type of component') help='the upper feeder limit for each type of component')
params = parser.parse_args() params = parser.parse_args()

View File

@ -1,14 +1,14 @@
# implementation of <<An integrated allocation method for the PCB assembly line balancing problem with nozzle changes>>
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from base_optimizer.optimizer_common import * from base_optimizer.optimizer_common import *
def selective_initialization(component_points, component_feeders, population_size): def selective_initialization(component_points, component_feeders, population_size):
population = [] # population initialization population = [] # population initialization
for _ in range(population_size): for _ in range(population_size):
individual = [] individual = []
for part_index, points in component_points.items(): for part_index, points in component_points:
if points == 0: if points == 0:
continue continue
# 可用机器数 # 可用机器数
@ -50,7 +50,7 @@ def selective_crossover(component_points, component_feeders, mother, father, non
one_counter, feasible_cut_line = 0, [] one_counter, feasible_cut_line = 0, []
idx = 0 idx = 0
for part_index, points in component_points.items(): for part_index, points in component_points:
one_counter = 0 one_counter = 0
idx_, mother_cut_line, father_cut_line = 0, [-1], [-1] idx_, mother_cut_line, father_cut_line = 0, [-1], [-1]
@ -136,7 +136,7 @@ def cal_individual_val(component_points, component_nozzle, individual):
machine_component_points = [[] for _ in range(max_machine_index)] machine_component_points = [[] for _ in range(max_machine_index)]
# decode the component allocation # decode the component allocation
for points in component_points.values(): for _, points in component_points:
component_gene = individual[idx: idx + points + max_machine_index - 1] component_gene = individual[idx: idx + points + max_machine_index - 1]
machine_idx, component_counter = 0, 0 machine_idx, component_counter = 0, 0
for gene in component_gene: for gene in component_gene:
@ -206,6 +206,7 @@ def assemblyline_optimizer_genetic(pcb_data, component_data):
# crossover rate & mutation rate: 80% & 10% # crossover rate & mutation rate: 80% & 10%
# population size: 200 # population size: 200
# the number of generation: 500 # the number of generation: 500
np.random.seed(0)
crossover_rate, mutation_rate = 0.8, 0.1 crossover_rate, mutation_rate = 0.8, 0.1
population_size, n_generations = 200, 500 population_size, n_generations = 200, 500
@ -219,6 +220,8 @@ def assemblyline_optimizer_genetic(pcb_data, component_data):
component_feeders[part_index] = component_data.loc[part_index]['feeder-limit'] component_feeders[part_index] = component_data.loc[part_index]['feeder-limit']
component_nozzle[part_index] = nozzle component_nozzle[part_index] = nozzle
component_points = sorted(component_points.items(), key=lambda x: x[0]) # 决定染色体排列顺序
# population initialization # population initialization
best_popval = [] best_popval = []
population = selective_initialization(component_points, component_feeders, population_size) population = selective_initialization(component_points, component_feeders, population_size)

View File

@ -1,16 +1,157 @@
import math
import numpy as np
from base_optimizer.optimizer_common import * from base_optimizer.optimizer_common import *
from ortools.sat.python import cp_model
# TODO: 需要考虑贴装点分布位置的限制 # TODO: consider with the PCB placement topology
def assembly_time_estimator(pcb_data, component_data, assignment): def assembly_time_estimator(component_points, component_feeders, component_nozzle, assignment_points):
return 0 # todo: how to deal with nozzle change
n_cycle, n_nz_change, n_gang_pick = 0, 0, 0
nozzle_heads, nozzle_points = defaultdict(int), defaultdict(int)
for idx, points in enumerate(assignment_points):
if points == 0:
continue
nozzle_points[component_nozzle[idx]] += points
nozzle_heads[component_nozzle[idx]] = 1
while sum(nozzle_heads.values()) != max_head_index:
max_cycle_nozzle = None
for nozzle, head_num in nozzle_heads.items():
if max_cycle_nozzle is None or nozzle_points[nozzle] / head_num > nozzle_points[max_cycle_nozzle] / \
nozzle_heads[max_cycle_nozzle]:
max_cycle_nozzle = nozzle
assert max_cycle_nozzle is not None
nozzle_heads[max_cycle_nozzle] += 1
n_cycle = max(map(lambda x: math.ceil(nozzle_points[x[0]] / x[1]), nozzle_heads.items()))
# calculate the number of simultaneous pickup
head_index, nozzle_cycle = 0, [[] for _ in range(max_head_index)]
for nozzle, heads in nozzle_heads.items():
head_index_cpy, points = head_index, nozzle_points[nozzle]
for _ in range(heads):
nozzle_cycle[head_index].append([nozzle, points // heads])
head_index += 1
points %= heads
while points:
nozzle_cycle[head_index_cpy][1] += 1
points -= 1
head_index_cpy += 1
# nozzle_cycle_index = [0 for _ in range(max_head_index)]
return n_cycle, n_nz_change, n_gang_pick
def assemblyline_optimizer_heuristic(pcb_data, component_data): def assemblyline_optimizer_heuristic(pcb_data, component_data):
assignment_result = [] # the number of placement points, the number of available feeders, and nozzle type of component respectively
component_number = len(component_data)
component_points = [0 for _ in range(component_number)]
component_feeders = [0 for _ in range(component_number)]
component_nozzle = [0 for _ in range(component_number)]
component_part = [0 for _ in range(component_number)]
# for machine_index in range(max_machine_index): nozzle_points = defaultdict(int) # the number of placements of nozzle
# assembly_time_estimator(pcb_data, component_data, assignment_result[machine_index])
for _, data in pcb_data.iterrows():
part_index = component_data[component_data['part'] == data['part']].index.tolist()[0]
nozzle = component_data.loc[part_index]['nz']
component_points[part_index] += 1
component_feeders[part_index] = component_data.loc[part_index]['feeder-limit']
# component_feeders[part_index] = math.ceil(component_data.loc[part_index]['feeder-limit'] / max_feeder_limit)
component_nozzle[part_index] = nozzle
component_part[part_index] = data['part']
nozzle_points[nozzle] += 1
# first step: generate the initial solution with equalized workload
assignment_result = [[0 for _ in range(len(component_points))] for _ in range(max_machine_index)]
assignment_points = [0 for _ in range(max_machine_index)]
# for part, points in enumerate(component_points):
# if component_nozzle[part] == 'CN065':
# assignment_result[1][part] += points
# assignment_points[1] += points
# component_points[part] = 0
# elif component_nozzle[part] == 'CN220':
# assignment_result[2][part] += points
# assignment_points[2] += points
# component_points[part] = 0
weighted_points = list(
map(lambda x: x[1] + 1e-5 * nozzle_points[component_nozzle[x[0]]], enumerate(component_points)))
for part_index in np.argsort(weighted_points):
if (total_points := component_points[part_index]) == 0: # total placements for each component type
continue
machine_set = []
# define the machine that assigning placement points (considering the feeder limitation)
for machine_index in np.argsort(assignment_points):
if len(machine_set) >= component_points[part_index] or len(machine_set) >= component_feeders[part_index]:
break
machine_set.append(machine_index)
# Allocation of mounting points to available machines according to the principle of equality
while total_points:
assign_machine = list(filter(lambda x: assignment_points[x] == min(assignment_points), machine_set))
if len(assign_machine) == len(machine_set):
# averagely assign point to all available machines
points = total_points // len(assign_machine)
for machine_index in machine_set:
assignment_points[machine_index] += points
assignment_result[machine_index][part_index] += points
total_points -= points * len(assign_machine)
for machine_index in machine_set:
if total_points == 0:
break
assignment_points[machine_index] += 1
assignment_result[machine_index][part_index] += 1
total_points -= 1
else:
# assigning placements to make up for the gap between the least and the second least
second_least_machine, second_least_machine_points = -1, max(assignment_points) + 1
for idx in machine_set:
if assignment_points[idx] < second_least_machine_points and assignment_points[idx] != min(
assignment_points):
second_least_machine_points = assignment_points[idx]
second_least_machine = idx
assert second_least_machine != -1
if len(assign_machine) * (second_least_machine_points - min(assignment_points)) < total_points:
min_points = min(assignment_points)
total_points -= len(assign_machine) * (second_least_machine_points - min_points)
for machine_index in assign_machine:
assignment_points[machine_index] += (second_least_machine_points - min_points)
assignment_result[machine_index][part_index] += (
second_least_machine_points - min_points)
else:
points = total_points // len(assign_machine)
for machine_index in assign_machine:
assignment_points[machine_index] += points
assignment_result[machine_index][part_index] += points
total_points -= points * len(assign_machine)
for machine_index in assign_machine:
if total_points == 0:
break
assignment_points[machine_index] += 1
assignment_result[machine_index][part_index] += 1
total_points -= 1
# todo: implementation
# second step: estimate the assembly time for each machine
# third step: adjust the assignment results to reduce maximal assembly time among all machines
return assignment_result return assignment_result

11
optimizer_spidermonkey.py Normal file
View File

@ -0,0 +1,11 @@
# implementation of
# <<Hybrid spider monkey optimisation algorithm for multi-level planning and scheduling problems of assembly lines>>
def assemblyline_optimizer_spidermonkey(pcb_data, component_data):
# number of swarms: 10
# maximum number of groups: 5
# number of loops: 100
# food source population: 50
# mutation rate: 0.1
# crossover rate: 0.9
# computation time(s): 200
pass

View File

@ -362,14 +362,24 @@ def optimization_assign_result(component_data, pcb_data, component_result, cycle
nozzle_assign = pd.DataFrame(columns=columns) nozzle_assign = pd.DataFrame(columns=columns)
for cycle, components in enumerate(component_result): for cycle, components in enumerate(component_result):
nozzle_assign.loc[cycle, 'cycle'] = cycle_result[cycle] nozzle_assign_row = len(nozzle_assign)
nozzle_assign.loc[nozzle_assign_row, 'cycle'] = cycle_result[cycle]
for head in range(max_head_index): for head in range(max_head_index):
index = component_result[cycle][head] index = component_result[cycle][head]
if index == -1: if index == -1:
nozzle_assign.loc[cycle, 'H{}'.format(head + 1)] = '' nozzle_assign.loc[nozzle_assign_row, 'H{}'.format(head + 1)] = ''
else: else:
nozzle = component_data.loc[index]['nz'] nozzle = component_data.loc[index]['nz']
nozzle_assign.loc[cycle, 'H{}'.format(head + 1)] = nozzle nozzle_assign.loc[nozzle_assign_row, 'H{}'.format(head + 1)] = nozzle
for head in range(max_head_index):
if nozzle_assign_row == 0 or nozzle_assign.loc[nozzle_assign_row - 1, 'H{}'.format(head + 1)] != \
nozzle_assign.loc[nozzle_assign_row, 'H{}'.format(head + 1)]:
break
else:
nozzle_assign.loc[nozzle_assign_row - 1, 'cycle'] += nozzle_assign.loc[nozzle_assign_row, 'cycle']
nozzle_assign.drop([len(nozzle_assign) - 1], inplace=True)
print(nozzle_assign) print(nozzle_assign)
print('') print('')
@ -449,17 +459,13 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
warnings.warn(info, UserWarning) warnings.warn(info, UserWarning)
return 0. return 0.
t_pick, t_place = .078, .051 # 贴装/拾取用时 total_pickup_time, total_round_time, total_place_time = .0, .0, 0 # 拾取用时、往返用时、贴装用时
t_nozzle_put, t_nozzle_pick = 0.9, 0.75 # 装卸吸嘴用时 total_operation_time = .0 # 操作用时
t_fix_camera_check = 0.12 # 固定相机检测时间 total_nozzle_change_counter = 0 # 总吸嘴更换次数
total_pick_counter = 0 # 总拾取次数
total_moving_time = .0 # 总移动用时 total_mount_distance, total_pick_distance = .0, .0 # 贴装距离、拾取距离
total_operation_time = .0 # 操作用时 total_distance = 0 # 总移动距离
total_nozzle_change_counter = 0 # 总吸嘴更换次数 cur_pos, next_pos = anc_marker_pos, [0, 0] # 贴装头当前位置
total_pick_counter = 0 # 总拾取次数
total_mount_distance, total_pick_distance = .0, .0 # 贴装距离、拾取距离
total_distance = 0 # 总移动距离
cur_pos, next_pos = anc_marker_pos, [0, 0] # 贴装头当前位置
# 初始化首个周期的吸嘴装配信息 # 初始化首个周期的吸嘴装配信息
nozzle_assigned = ['Empty' for _ in range(max_head_index)] nozzle_assigned = ['Empty' for _ in range(max_head_index)]
@ -492,8 +498,10 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
# ANC处进行吸嘴更换 # ANC处进行吸嘴更换
if nozzle_pick_counter + nozzle_put_counter > 0: if nozzle_pick_counter + nozzle_put_counter > 0:
next_pos = anc_marker_pos next_pos = anc_marker_pos
total_moving_time += max(axis_moving_time(cur_pos[0] - next_pos[0], 0), move_time = max(axis_moving_time(cur_pos[0] - next_pos[0], 0),
axis_moving_time(cur_pos[1] - next_pos[1], 1)) axis_moving_time(cur_pos[1] - next_pos[1], 1))
total_round_time += move_time
total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1]))
cur_pos = next_pos cur_pos = next_pos
@ -501,15 +509,21 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
pick_slot = sorted(pick_slot, reverse=True) pick_slot = sorted(pick_slot, reverse=True)
# 拾取路径(自右向左) # 拾取路径(自右向左)
for slot in pick_slot: for idx, slot in enumerate(pick_slot):
if slot < max_slot_index // 2: if slot < max_slot_index // 2:
next_pos = [slotf1_pos[0] + slot_interval * (slot - 1), slotf1_pos[1]] next_pos = [slotf1_pos[0] + slot_interval * (slot - 1), slotf1_pos[1]]
else: else:
next_pos = [slotr1_pos[0] - slot_interval * (max_slot_index - slot - 1), slotr1_pos[1]] next_pos = [slotr1_pos[0] - slot_interval * (max_slot_index - slot - 1), slotr1_pos[1]]
total_operation_time += t_pick total_operation_time += t_pick
total_pick_counter += 1 total_pick_counter += 1
total_moving_time += max(axis_moving_time(cur_pos[0] - next_pos[0], 0),
axis_moving_time(cur_pos[1] - next_pos[1], 1)) move_time = max(axis_moving_time(cur_pos[0] - next_pos[0], 0),
axis_moving_time(cur_pos[1] - next_pos[1], 1))
if idx == 0:
total_round_time += move_time
else:
total_pickup_time += move_time
total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1]))
if slot != pick_slot[0]: if slot != pick_slot[0]:
total_pick_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) total_pick_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1]))
@ -522,8 +536,10 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
camera = component_data.loc[component_result[cycle_set][head]]['camera'] camera = component_data.loc[component_result[cycle_set][head]]['camera']
if camera == '固定相机': if camera == '固定相机':
next_pos = [fix_camera_pos[0] - head * head_interval, fix_camera_pos[1]] next_pos = [fix_camera_pos[0] - head * head_interval, fix_camera_pos[1]]
total_moving_time += max(axis_moving_time(cur_pos[0] - next_pos[0], 0), move_time = max(axis_moving_time(cur_pos[0] - next_pos[0], 0),
axis_moving_time(cur_pos[1] - next_pos[1], 1)) axis_moving_time(cur_pos[1] - next_pos[1], 1))
total_round_time += move_time
total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1]))
total_operation_time += t_fix_camera_check total_operation_time += t_fix_camera_check
cur_pos = next_pos cur_pos = next_pos
@ -545,22 +561,26 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
# 考虑R轴预旋转补偿同轴角度转动带来的额外贴装用时 # 考虑R轴预旋转补偿同轴角度转动带来的额外贴装用时
total_operation_time += head_rotary_time(mount_angle[0]) # 补偿角度转动带来的额外贴装用时 total_operation_time += head_rotary_time(mount_angle[0]) # 补偿角度转动带来的额外贴装用时
total_operation_time += t_nozzle_put * nozzle_put_counter + t_nozzle_pick * nozzle_pick_counter total_operation_time += t_nozzle_put * nozzle_put_counter + t_nozzle_pick * nozzle_pick_counter
for pos in mount_pos: for idx, pos in enumerate(mount_pos):
total_operation_time += t_place total_operation_time += t_place
total_moving_time += max(axis_moving_time(cur_pos[0] - pos[0], 0), move_time = max(axis_moving_time(cur_pos[0] - pos[0], 0), axis_moving_time(cur_pos[1] - pos[1], 1))
axis_moving_time(cur_pos[1] - pos[1], 1)) if idx == 0:
total_round_time += move_time
else:
total_place_time += move_time
total_distance += max(abs(cur_pos[0] - pos[0]), abs(cur_pos[1] - pos[1])) total_distance += max(abs(cur_pos[0] - pos[0]), abs(cur_pos[1] - pos[1]))
cur_pos = pos cur_pos = pos
total_nozzle_change_counter += nozzle_put_counter + nozzle_pick_counter total_nozzle_change_counter += nozzle_put_counter + nozzle_pick_counter
total_time = total_moving_time + total_operation_time total_time = total_pickup_time + total_round_time + total_place_time + total_operation_time
minutes, seconds = int(total_time // 60), int(total_time) % 60 minutes, seconds = int(total_time // 60), int(total_time) % 60
millisecond = int((total_time - minutes * 60 - seconds) * 60) millisecond = int((total_time - minutes * 60 - seconds) * 60)
if hinter: if hinter:
optimization_assign_result(component_data, pcb_data, component_result, cycle_result, feeder_slot_result, optimization_assign_result(component_data, pcb_data, component_result, cycle_result, feeder_slot_result,
nozzle_hinter=True, component_hinter=True, feeder_hinter=True) nozzle_hinter=False, component_hinter=False, feeder_hinter=False)
print('-Cycle counter: {}'.format(sum(cycle_result))) print('-Cycle counter: {}'.format(sum(cycle_result)))
print('-Nozzle change counter: {}'.format(total_nozzle_change_counter // 2)) print('-Nozzle change counter: {}'.format(total_nozzle_change_counter // 2))
@ -570,7 +590,9 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re
print('-Expected picking tour length: {} mm'.format(total_pick_distance)) print('-Expected picking tour length: {} mm'.format(total_pick_distance))
print('-Expected total tour length: {} mm'.format(total_distance)) print('-Expected total tour length: {} mm'.format(total_distance))
print('-Expected total moving time: {} s'.format(total_moving_time)) print('-Expected total moving time: {} s with pick: {}, round: {}, place = {}'.format(
total_pickup_time + total_round_time + total_place_time, total_pickup_time, total_round_time,
total_place_time))
print('-Expected total operation time: {} s'.format(total_operation_time)) print('-Expected total operation time: {} s'.format(total_operation_time))
if minutes > 0: if minutes > 0: