diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 89e08fb..0000000 --- a/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/base_optimizer/optimizer_aggregation.py b/base_optimizer/optimizer_aggregation.py index 4e383df..c7ba874 100644 --- a/base_optimizer/optimizer_aggregation.py +++ b/base_optimizer/optimizer_aggregation.py @@ -1,15 +1,18 @@ from base_optimizer.optimizer_common import * -from ortools.sat.python import cp_model +from gurobipy import * 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 def optimizer_aggregation(component_data, pcb_data): # === phase 0: data preparation === M = 1000 # a sufficient large number 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) 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 nozzle_list[nozzle] += 1 - I, J = len(component_list.keys()), len(nozzle_list.keys()) - L = I + 1 - HC = [[M for _ in range(J)] for _ in range(I)] # the handing class when component i is handled by nozzle type j - # represent the nozzle-component compatibility + I, J = len(component_list.keys()), len(nozzle_list.keys()) # the maximum number of component types and nozzle types + L = I + 1 # the maximum number of batch level + K = max_head_index # the maximum number of heads + HC = [[M for _ in range(J)] for _ in range(I)] # represent the nozzle-component compatibility + for i in range(I): for _, item in enumerate(cpidx_2_part.items()): index, part = item @@ -41,105 +45,71 @@ def optimizer_aggregation(component_data, pcb_data): HC[index][j] = 0 # === phase 1: mathematical model solver === - model = cp_model.CpModel() - solver = cp_model.CpSolver() + mdl = Model('SMT') + mdl.setParam('OutputFlag', 0) # === Decision Variables === # the number of components of type i that are placed by nozzle type j on placement head k - X = {} - 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)) + X = mdl.addVars(list_range(I), list_range(J), list_range(K), vtype=GRB.INTEGER, ub=max(component_list.values())) # the total number of nozzle changes on placement head k - N = {} - for k in range(K): - N[k] = model.NewIntVar(0, J, 'N_{}'.format(k)) + N = mdl.addVars(list_range(K), vtype=GRB.INTEGER) # 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 - Z = {} - 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)) + Z = mdl.addVars(list_range(I), list_range(J), list_range(L), list_range(K), vtype=GRB.BINARY) # 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 - D = {} - for l in range(L): - for k in range(K): - D[l, k] = model.NewIntVar(0, 2, 'D_{}_{}'.format(l, k)) - - 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)) + # Dlk := 0 otherwise + D = mdl.addVars(list_range(L), list_range(K), vtype=GRB.BINARY, ub=2) + D_plus = mdl.addVars(list_range(L), list_range(J), list_range(K), vtype=GRB.INTEGER) + D_minus = mdl.addVars(list_range(L), list_range(J), list_range(K), vtype=GRB.INTEGER) # == 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 === - for i in range(I): - model.Add(sum(X[i, j, k] for j in range(J) for k in range(K)) == component_list[cpidx_2_part[i]]) + mdl.addConstrs( + 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): - model.Add(sum(X[i, j, k] for i in range(I) for j in range(J)) <= WL) + mdl.addConstrs(quicksum(X[i, j, k] for i in range(I) for j in range(J)) <= WL for k in range(K)) - for i in range(I): - for j in range(J): - for k in range(K): - model.Add(X[i, j, k] <= M * sum(Z[i, j, l, k] for l in range(L))) + mdl.addConstrs( + 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 + range(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) + 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)) + mdl.addConstrs( + 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)) - 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)) <= X[i, j, k]) + mdl.addConstrs(quicksum(Z[i, j, l, k] for j in range(J) for i in range(I)) >= quicksum( + 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): - for l in range(L - 1): - 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 j in range(J) for i in range(I))) + 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)) + mdl.addConstrs(D_plus[l, j, k] - D_minus[l, j, k] == quicksum(Z[i, j, l, k] for i in range(I)) - quicksum( + 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)) - for l in range(I): - for k in range(K): - model.Add(sum(Z[i, j, l, k] for i in range(I) for j in range(J)) <= 1) + mdl.addConstrs( + 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 + range(L)) - for l in range(L - 1): - for j in range(J): - 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))) + mdl.addConstrs(2 * N[k] == quicksum(D[l, k] for l in range(L)) - 1 for k in range(K)) + mdl.addConstrs( + 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)) # === Main Process === component_result, cycle_result = [], [] feeder_slot_result, placement_result, head_sequence = [], [], [] - solver.parameters.max_time_in_seconds = 20.0 + mdl.setParam("TimeLimit", 100) - status = solver.Solve(model) - if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE: - print('total cost = {}'.format(solver.ObjectiveValue())) + mdl.optimize() + + if mdl.Status == GRB.OPTIMAL: + print('total cost = {}'.format(mdl.objval)) # convert cp model solution to standard output model_cycle_result, model_component_result = [], [] @@ -149,9 +119,9 @@ def optimizer_aggregation(component_data, pcb_data): for k in range(K): for i in range(I): 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_cycle_result[-1][k] = solver.Value(X[i, j, k]) + model_cycle_result[-1][k] = round(X[i, j, k].x) # remove redundant term 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: continue index_ = component_result[cycle_idx][head] - placement_result[-1][head] = mount_point_pos[index_][-1][2] mount_point_pos[index_].pop() head_sequence.append(dynamic_programming_cycle_path(pcb_data, placement_result[-1], feeder_slot_result[cycle_idx])) diff --git a/base_optimizer/optimizer_common.py b/base_optimizer/optimizer_common.py index 95a1d68..9307366 100644 --- a/base_optimizer/optimizer_common.py +++ b/base_optimizer/optimizer_common.py @@ -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} +# 时间参数 +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): distance = abs(distance) * 1e-3 @@ -880,7 +886,7 @@ def constraint_swap_mutation(component_points, individual): offspring = individual.copy() 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: while True: index1, index2 = random.sample(range(points + max_machine_index - 2), 2) diff --git a/base_optimizer/optimizer_feederpriority.py b/base_optimizer/optimizer_feederpriority.py index 2dbb071..5d27d46 100644 --- a/base_optimizer/optimizer_feederpriority.py +++ b/base_optimizer/optimizer_feederpriority.py @@ -2,7 +2,7 @@ from base_optimizer.optimizer_common import * @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) # 供料器贴装点数 mount_center_pos = defaultdict(int) diff --git a/base_optimizer/optimizer_hybridgenetic.py b/base_optimizer/optimizer_hybridgenetic.py index 609be78..f740508 100644 --- a/base_optimizer/optimizer_hybridgenetic.py +++ b/base_optimizer/optimizer_hybridgenetic.py @@ -234,8 +234,8 @@ def cal_individual_val(component_nozzle, component_point_pos, designated_nozzle, 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, - pair_group, feeder_lane, individual): +def convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group, + pickup_group_cycle, pair_group, feeder_lane, individual): component_result, cycle_result, feeder_slot_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] # 检查槽位占用情况 - if feeder_lane[slot] is not None and pick_part is not None: + if feeder_lane[slot] and pick_part: assign_available = False break # 检查机械限位冲突 - if pick_part is not None and (slot - CT_Head[pick_part][0] * interval_ratio <= 0 or - slot + (max_head_index - CT_Head[pick_part][1] - 1) * interval_ratio > max_slot_index // 2): + if pick_part and (slot - CT_Head[pick_part][0] * interval_ratio <= 0 or slot + ( + max_head_index - CT_Head[pick_part][1] - 1) * interval_ratio > max_slot_index // 2): assign_available = False break if assign_available: for idx, component in enumerate(pickup): - if component is not None: + if component: feeder_lane[assign_slot + idx * interval_ratio] = component CT_Group_slot[CTIdx] = assign_slot break @@ -509,32 +509,31 @@ def optimizer_hybrid_genetic(pcb_data, component_data, hinter=True): with tqdm(total=n_generations) as pbar: 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): - # 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) - - 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]) + # 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 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 c = 0 - new_population = [] + new_population, new_pop_val = [], [] for pop in range(population_size): 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: - index2 = roulette_wheel_selection(pop_val) + index2 = roulette_wheel_selection(convert_pop_val) if index1 != index2: break # 两点交叉算子 @@ -552,13 +551,27 @@ def optimizer_hybrid_genetic(pcb_data, component_data, hinter=True): new_population.append(offspring1) new_population.append(offspring2) - # selection - top_k_index = get_top_k_value(pop_val, population_size - len(new_population)) + val, _, _ = cal_individual_val(component_nozzle, component_point_pos, designated_nozzle, + 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: new_population.append(population[index]) + new_pop_val.append(pop_val[index]) population = new_population + pop_val = new_pop_val pbar.update(1) + best_individual = population[np.argmin(pop_val)] + return convert_individual_2_result(component_data, component_point_pos, designated_nozzle, pickup_group, pickup_group_cycle, pair_group, feeder_lane, best_individual) diff --git a/base_optimizer/optimizer_scanbased.py b/base_optimizer/optimizer_scanbased.py index d6a9cc3..6f4c12b 100644 --- a/base_optimizer/optimizer_scanbased.py +++ b/base_optimizer/optimizer_scanbased.py @@ -3,11 +3,11 @@ from base_optimizer.optimizer_common import * @timer_wrapper -def optimizer_scanbased(component_data, pcb_data, hinter): +def optimizer_genetic_scanning(component_data, pcb_data, hinter): population_size = 200 # 种群规模 crossover_rate, mutation_rate = .4, .02 - n_generation = 5 + n_generation = 500 component_points = [0] * len(component_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)) - # todo: 过程写的有问题,暂时不想改 + sigma_scaling(pop_val, 1) + with tqdm(total=n_generation) as pbar: 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 pop in range(population_size): 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: - index2 = roulette_wheel_selection(pop_val) + index2 = roulette_wheel_selection(convert_pop_val) if index1 != index2: break # 两点交叉算子 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) - pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) - pop_individual.append(offspring1) + new_pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) + new_pop_individual.append(offspring1) _, cycle_result, feeder_slot_result = convert_individual_2_result(component_points, offspring2) - pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) - pop_individual.append(offspring2) + new_pop_val.append(feeder_arrange_evaluate(feeder_slot_result, cycle_result)) + 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]) - # 变异 - if np.random.random() < mutation_rate: - 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 + pop_individual, pop_val = new_pop_individual, new_pop_val + sigma_scaling(pop_val, 1) # select the best individual 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] # TODO: 暂时未考虑可用吸嘴数的限制 - # for _ in range(math.ceil(sum(component_points) / max_head_index)): while True: # === 周期内循环 === assigned_part = [-1 for _ in range(max_head_index)] # 当前扫描到的头分配元件信息 diff --git a/dataloader.py b/dataloader.py index e73e200..dd91718 100644 --- a/dataloader.py +++ b/dataloader.py @@ -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_col = ["part", "desc", "fdr", "nz", 'camera', 'group', 'feeder-limit'] + part_col = ["part", "desc", "fdr", "nz", 'camera', 'group', 'feeder-limit', 'points'] try: if load_cp_data: 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(): part, nozzle = data.part, data.nz.split(' ')[1] slot = data['fdr'].split(' ')[0] - if part not in component_data['part'].values: if not cp_auto_register: raise Exception("unregistered component: " + component_data['part'].values) else: 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) # warning_info = 'register component ' + part + ' with default feeder type' # warnings.warn(warning_info, UserWarning) part_index = component_data[component_data['part'] == part].index.tolist()[0] part_feeder_assign[part].add(slot) + component_data.loc[part_index]['points'] += 1 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' @@ -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表示是否为预分配,不表示分配数目 if load_feeder_data: - for data in pcb_data.iterrows(): - fdr = data[1]['fdr'] - slot, part = fdr.split(' ') + for _, data in pcb_data.iterrows(): + slot, part = data['fdr'].split(' ') if slot[0] != 'F' and slot[0] != 'R': continue 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) - # plt.scatter(pcb_data["x"], pcb_data["y"]) - # plt.show() + pcb_data = pcb_data.sort_values(by="x", ascending=False) return pcb_data, component_data, feeder_data diff --git a/optimizer.py b/optimizer.py index 5cfa5ec..6727bed 100644 --- a/optimizer.py +++ b/optimizer.py @@ -1,24 +1,34 @@ +import copy import math import matplotlib.pyplot as plt import pandas as pd -from base_optimizer.optimizer_aggregation import * from base_optimizer.optimizer_scanbased import * from base_optimizer.optimizer_celldivision import * from base_optimizer.optimizer_hybridgenetic import * from base_optimizer.optimizer_feederpriority import * - from dataloader import * from optimizer_genetic import * from optimizer_heuristic import * -def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_optimizer): - assignment_result = assemblyline_optimizer_genetic(pcb_data, component_data) +def deviation(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 = [], [] partial_pcb_data, partial_component_data = defaultdict(pd.DataFrame), defaultdict(pd.DataFrame) for machine_index in range(max_machine_index): @@ -26,7 +36,9 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_ partial_component_data[machine_index] = component_data.copy(deep=True) 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(): feeder_limit = data['feeder-limit'] feeder_points = [assignment_result[machine_index][part_index] for machine_index in range(max_machine_index)] @@ -49,11 +61,14 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_ partial_component_data[machine_index].loc[part_index]['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))] - pcb_data = pcb_data.sort_values(by="x", ascending=False) for _, data in pcb_data.iterrows(): - part = data['part'] - part_index = component_data[component_data['part'] == part].index.tolist()[0] + part_index = component_data[component_data['part'] == data['part']].index.tolist()[0] while True: machine_index = component_machine_index[part_index] if assignment_result[machine_index][part_index] == 0: @@ -64,11 +79,60 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_ assignment_result[machine_index][part_index] -= 1 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(): data = data.reset_index(drop=True) if len(data) == 0: 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], feeder_data=pd.DataFrame(columns=['slot', 'part', 'arg']), method=single_machine_optimizer, hinter=True)) @@ -86,13 +150,15 @@ def optimizer(pcb_data, component_data, assembly_line_optimizer, single_machine_ # todo: 不同类型元件的组装时间差异 def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, method='', hinter=False): + 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, cycle_result, feeder_slot_result) - elif method == 'feeder_priority': # 基于基座扫描的供料器优先算法 + elif method == 'feeder_scan': # 基于基座扫描的供料器优先算法 # 第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步:扫描供料器基座,确定元件拾取的先后顺序 component_result, cycle_result, feeder_slot_result = feeder_base_scan(component_data, pcb_data, feeder_data, nozzle_pattern) @@ -105,25 +171,26 @@ def base_optimizer(machine_index, pcb_data, component_data, feeder_data=None, me elif method == '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的整数规划 + 启发式算法 component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_aggregation( component_data, pcb_data) - elif method == 'scan_based': - component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_scanbased( - component_data, pcb_data, False) + elif method == 'genetic_scanning': + component_result, cycle_result, feeder_slot_result, placement_result, head_sequence = optimizer_genetic_scanning( + component_data, pcb_data, hinter=False) else: raise 'method is not existed' if hinter: 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('-Cycle counter: {}'.format(sum(cycle_result))) 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]] for cycle in range(len(cycle_result)): @@ -141,25 +208,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) 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('-Pick operation counter: {}'.format(total_pick_counter)) + print('-Pick movement: {}'.format(total_pick_movement)) print('------------------------------ ') # 估算贴装用时 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(): # warnings.simplefilter('ignore') # 参数解析 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('--base_optimizer', default='feeder_priority', type=str, - help='base optimizer for single machine') - parser.add_argument('--assembly_optimizer', default='genetic', type=str, help='optimizer for PCB Assembly Line') - parser.add_argument('--feeder_limit', default=2, type=int, + parser.add_argument('--base_optimizer', default='feeder_scan', type=str, help='base optimizer for single machine') + parser.add_argument('--assembly_optimizer', default='heuristic', type=str, help='optimizer for PCB Assembly Line') + parser.add_argument('--feeder_limit', default=1, type=int, help='the upper feeder limit for each type of component') params = parser.parse_args() diff --git a/optimizer_genetic.py b/optimizer_genetic.py index f514fa7..9795df9 100644 --- a/optimizer_genetic.py +++ b/optimizer_genetic.py @@ -236,7 +236,10 @@ def cal_individual_val(component_points, component_nozzle, individual): for idx in range(len(heads_placement) // max_head_index): wl += heads_placement[idx][1] objective_val.append(T_pp * machine_points + T_tr * wl + T_nc * ul + T_pl * pl) +<<<<<<< HEAD +======= +>>>>>>> 87ddb057cadf152d7af793aa7b8da439dedbe361 return objective_val, machine_component_points @@ -246,7 +249,7 @@ def assemblyline_optimizer_genetic(pcb_data, component_data): # population size: 200 # the number of generation: 500 crossover_rate, mutation_rate = 0.8, 0.1 - population_size, n_generations = 200, 500 + population_size, n_generations = 500, 500 # the number of placement points, the number of available feeders, and nozzle type of component respectively component_points, component_feeders, component_nozzle = defaultdict(int), defaultdict(int), defaultdict(str) @@ -275,8 +278,7 @@ def assemblyline_optimizer_genetic(pcb_data, component_data): pop_val.append(max(val)) best_popval.append(min(pop_val)) - - select_index = get_top_k_value(pop_val, population_size - len(new_pop_val), reverse=False) + select_index = get_top_k_value(pop_val, population_size - len(new_population), reverse=False) population = [population[idx] for idx in select_index] pop_val = [pop_val[idx] for idx in select_index] diff --git a/optimizer_heuristic.py b/optimizer_heuristic.py index 3ca559f..c9ac196 100644 --- a/optimizer_heuristic.py +++ b/optimizer_heuristic.py @@ -1,16 +1,146 @@ +import math +import numpy as np + from base_optimizer.optimizer_common import * -# TODO: 需要考虑贴装点分布位置的限制 -def assembly_time_estimator(pcb_data, component_data, assignment): - return 0 +# TODO: consider with the PCB placement topology +def assembly_time_estimator(component_points, component_feeders, component_nozzle, assignment_points): + # 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): - 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): - # assembly_time_estimator(pcb_data, component_data, assignment_result[machine_index]) + nozzle_points = defaultdict(int) # the number of placements of nozzle + + 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)] + + 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 diff --git a/optimizer_spidermonkey.py b/optimizer_spidermonkey.py new file mode 100644 index 0000000..eb3410d --- /dev/null +++ b/optimizer_spidermonkey.py @@ -0,0 +1,11 @@ +# implementation of +# <> +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 diff --git a/result_analysis.py b/result_analysis.py index d7d9866..5793d68 100644 --- a/result_analysis.py +++ b/result_analysis.py @@ -362,14 +362,24 @@ def optimization_assign_result(component_data, pcb_data, component_result, cycle nozzle_assign = pd.DataFrame(columns=columns) 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): index = component_result[cycle][head] if index == -1: - nozzle_assign.loc[cycle, 'H{}'.format(head + 1)] = '' + nozzle_assign.loc[nozzle_assign_row, 'H{}'.format(head + 1)] = '' else: 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('') @@ -449,17 +459,13 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re warnings.warn(info, UserWarning) return 0. - t_pick, t_place = .078, .051 # 贴装/拾取用时 - t_nozzle_put, t_nozzle_pick = 0.9, 0.75 # 装卸吸嘴用时 - t_fix_camera_check = 0.12 # 固定相机检测时间 - - total_moving_time = .0 # 总移动用时 - total_operation_time = .0 # 操作用时 - total_nozzle_change_counter = 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] # 贴装头当前位置 + total_pickup_time, total_round_time, total_place_time = .0, .0, 0 # 拾取用时、往返用时、贴装用时 + total_operation_time = .0 # 操作用时 + total_nozzle_change_counter = 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)] @@ -492,8 +498,10 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re # ANC处进行吸嘴更换 if nozzle_pick_counter + nozzle_put_counter > 0: next_pos = anc_marker_pos - 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)) + total_round_time += move_time + total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) 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) # 拾取路径(自右向左) - for slot in pick_slot: + for idx, slot in enumerate(pick_slot): if slot < max_slot_index // 2: next_pos = [slotf1_pos[0] + slot_interval * (slot - 1), slotf1_pos[1]] else: next_pos = [slotr1_pos[0] - slot_interval * (max_slot_index - slot - 1), slotr1_pos[1]] total_operation_time += t_pick 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])) if slot != pick_slot[0]: 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'] if camera == '固定相机': 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), - 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)) + total_round_time += move_time + total_distance += max(abs(cur_pos[0] - next_pos[0]), abs(cur_pos[1] - next_pos[1])) total_operation_time += t_fix_camera_check cur_pos = next_pos @@ -545,22 +561,26 @@ def placement_time_estimate(component_data, pcb_data, component_result, cycle_re # 考虑R轴预旋转,补偿同轴角度转动带来的额外贴装用时 total_operation_time += head_rotary_time(mount_angle[0]) # 补偿角度转动带来的额外贴装用时 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_moving_time += max(axis_moving_time(cur_pos[0] - pos[0], 0), - axis_moving_time(cur_pos[1] - pos[1], 1)) + move_time = max(axis_moving_time(cur_pos[0] - pos[0], 0), 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])) cur_pos = pos 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 millisecond = int((total_time - minutes * 60 - seconds) * 60) if hinter: 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('-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 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)) if minutes > 0: