1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
| from typing import Any from mcp.server.fastmcp import FastMCP import pandas as pd import numpy as np from sko.PSO import PSO import json import csv import random import heapq import sys import io from collections import defaultdict import os import types import warnings from abc import ABCMeta from types import MethodType, FunctionType from functools import lru_cache
np.random.seed(6)
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
TURN_COST = 1
LOAD_UNLOAD_TIME = 1
GRID_SIZE = (21, 21)
CSV_PATH = os.path.join(os.getcwd(), "agv_trajectory.csv")
def manhattan(p1, p2): """ 计算两点之间的曼哈顿距离 Args: p1 (tuple): 第一个点的坐标 (x, y) p2 (tuple): 第二个点的坐标 (x, y) Returns: int: 两点之间的曼哈顿距离 """ return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def get_orientation(from_pos, to_pos): """ 计算从一个位置到另一个位置的方向向量对应的朝向角度 Args: from_pos (tuple): 起始位置坐标 (x, y) to_pos (tuple): 目标位置坐标 (x, y) Returns: int/None: 朝向角度(0/90/180/270)或None(无方向变化) """ dx, dy = to_pos[0] - from_pos[0], to_pos[1] - from_pos[1] if dx > 0: return 0 elif dx < 0: return 180 elif dy > 0: return 90 elif dy < 0: return 270 else: return None
def a_star(start, goal, obstacles, grid_size=(21, 21)): """ 使用A*算法为AGV规划路径,AGV仅可以在X,Y方向移动 Args: start (tuple): 起始位置坐标 (x, y) goal (tuple): 目标位置坐标 (x, y) obstacles (set): 障碍物位置集合 grid_size (tuple): 网格大小 (默认为21x21) Returns: list: 从起始点到目标点的路径坐标列表,如果未找到路径则返回空列表 """ def neighbors(pos): """ 获取当前位置的所有有效邻居节点 Args: pos (tuple): 当前位置坐标 (x, y) Yields: tuple: 有效的邻居节点坐标 (x, y) """ x, y = pos for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nx, ny = x + dx, y + dy if 1 <= nx <= grid_size[0] and 1 <= ny <= grid_size[1] and (nx, ny) not in obstacles: yield (nx, ny)
frontier = [] heapq.heappush(frontier, (manhattan(start, goal), 0, start, [start])) visited = set()
while frontier: _, cost, current, path = heapq.heappop(frontier) if current == goal: return path if current in visited: continue visited.add(current) for neighbor in neighbors(current): if neighbor not in visited: heapq.heappush(frontier, (cost + 1 + manhattan(neighbor, goal), cost + 1, neighbor, path + [neighbor])) return []
def simulate_path_strict_load(name, path, start_time, initial_pitch, loaded, destination, emergency, taskid, start_point, task_queues, t_q): """ 模拟AGV从当前位置前往取料点取料的路径过程,严格满足AGV运动规则 Args: name (str): AGV名称 path (list): 路径坐标列表 start_time (int): 起始时间 initial_pitch (int): 初始朝向 loaded (bool): 是否已装载货物 destination (str): 目的地 emergency (bool): 是否为紧急任务 taskid (str): 任务ID start_point (str): 起始点名称 task_queues (dict): 任务队列 t_q (int): 任务可执行时间 Returns: tuple: (路径步骤列表, 最终时间, 最终朝向, 最终位置) """ steps = [] t = start_time pitch = initial_pitch last = path[0]
target_pickup_pos = path[-1]
for current in path[1:]: new_pitch = get_orientation(last, current)
if new_pitch != pitch: steps.append({ "timestamp": t, "name": name, "X": last[0], "Y": last[1], "pitch": new_pitch, "loaded": loaded, "destination": destination if loaded else "", "Emergency": False, "taskid": taskid }) pitch = new_pitch t += 1
steps.append({ "timestamp": t, "name": name, "X": current[0], "Y": current[1], "pitch": pitch, "loaded": loaded, "destination": destination if loaded else "", "Emergency": False, "taskid": taskid }) last = current t += 1
while True: first_task_id = task_queues[start_point][0]["task_id"] if task_queues[start_point] and len( task_queues[start_point]) > 0 else None if taskid == first_task_id and t >= t_q: break steps.append({ "timestamp": t, "name": name, "X": current[0], "Y": current[1], "pitch": pitch, "loaded": loaded, "destination": destination if loaded else "", "Emergency": False, "taskid": taskid }) t += 1
steps.append({ "timestamp": t, "name": name, "X": current[0], "Y": current[1], "pitch": pitch, "loaded": True, "destination": destination, "Emergency": emergency, "task-id": taskid })
return steps, t, pitch, last
def simulate_path_strict_unload(name, path, start_time, initial_pitch, loaded, destination, emergency, taskid): """ 模拟AGV从取料点到卸料点的路径过程,严格满足AGV运动规则 Args: name (str): AGV名称 path (list): 路径坐标列表 start_time (int): 起始时间 initial_pitch (int): 初始朝向 loaded (bool): 是否已装载货物 destination (str): 目的地 emergency (bool): 是否为紧急任务 taskid (str): 任务ID Returns: tuple: (路径步骤列表, 最终时间, 最终朝向, 最终位置) """ steps = [] t = start_time pitch = initial_pitch last = path[0]
for current in path[1:]: new_pitch = get_orientation(last, current)
if new_pitch != pitch: steps.append({ "timestamp": t, "name": name, "X": last[0], "Y": last[1], "pitch": new_pitch, "loaded": loaded, "destination": destination if loaded else "", "Emergency": emergency, "taskid": taskid }) pitch = new_pitch t += 1
steps.append({ "timestamp": t, "name": name, "X": current[0], "Y": current[1], "pitch": pitch, "loaded": loaded, "destination": destination if loaded else "", "Emergency": emergency, "taskid": taskid }) last = current t += 1
steps.append({ "timestamp": t, "name": name, "X": current[0], "Y": current[1], "pitch": pitch, "loaded": "false", "destination": "", "Emergency": "false", "task-id": taskid })
return steps, t, pitch, last
def reserve_simulated_steps(steps, reservation_table, agv_name): """ 将AGV的路径记录写入预约表,用于后续路径冲突判断 Args: steps (list): AGV路径步骤列表 reservation_table (dict): 预约表,键为(timestamp, (x, y)),值为AGV名称 agv_name (str): AGV名称 """ for step in steps: key = (step["timestamp"], (step["X"], step["Y"])) reservation_table[key] = agv_name
def init_csv(agv_list): """ 初始化CSV_PATH的AGV轨迹文件,timestamp=0需要在最终轨迹文件中体现 Args: agv_list (list): AGV列表,包含AGV的ID、位置和朝向信息 """ with open(CSV_PATH, 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(["timestamp", "name", "X", "Y", "pitch", "loaded", "destination", "Emergency", "task-id"]) for agv in agv_list: writer.writerow([ 0, agv["id"], agv["pose"][0], agv["pose"][1], agv["pitch"], "false", "", "false", "" ])
def append_to_csv(steps): """ 将路径步骤追加写入CSV文件 Args: steps (list): AGV路径步骤列表 """ with open(CSV_PATH, 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f) for step in steps: writer.writerow([ step["timestamp"], step["name"], step["X"], step["Y"], step["pitch"], str(step["loaded"]).lower(), step["destination"], str(step["Emergency"]).lower(), step.get("task-id", "") ])
def get_pickup_coord(start_point_name, original_coord): """ 根据起始点名称确定取料点坐标 Args: start_point_name (str): 起始点名称 original_coord (tuple): 原始坐标 (x, y) Returns: tuple: 取料点坐标 (x, y) """ if start_point_name in ["Tiger", "Dragon", "Horse"]: return (original_coord[0] + 1, original_coord[1]) else: return (original_coord[0] - 1, original_coord[1])
def get_delivery_options(dest_coord): """ 获取卸料点周围的4个可选位置 Args: dest_coord (tuple): 目标坐标 (x, y) Returns: list: 卸料点周围的4个可选位置坐标列表 """ x, y = dest_coord return [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
def is_head_on_swap_conflict(path_steps, reservation_table): """ 检查路径中是否存在对穿(head-on swap)冲突 Args: path_steps (list): 路径步骤列表 reservation_table (dict): 预约表 Returns: set: 冲突位置集合 {(x, y), ...} """ conflict_points = set() for i in range(len(path_steps) - 1): now = (path_steps[i]["timestamp"], (path_steps[i]["X"], path_steps[i]["Y"])) nxt = (path_steps[i + 1]["timestamp"], (path_steps[i + 1]["X"], path_steps[i + 1]["Y"]))
for (t, pos), other_agv in reservation_table.items(): if t == now[0] and pos == nxt[1]: back_key = (t + 1, now[1]) if back_key in reservation_table and reservation_table[back_key] == other_agv: conflict_points.add(now[1]) conflict_points.add(nxt[1]) return conflict_points
def is_conflict(path_steps, reservation_table): """ 检测路径步骤中是否有与已有预约路径冲突的情况 Args: path_steps (list): 路径步骤列表 reservation_table (dict): 预约表 Returns: tuple: (是否存在冲突(bool), 所有冲突位置的坐标集合(set)) """ conflict_points = set()
for step in path_steps: key = (step["timestamp"], (step["X"], step["Y"])) if key in reservation_table: conflict_points.add((step["X"], step["Y"]))
swap_points = is_head_on_swap_conflict(path_steps, reservation_table) conflict_points.update(swap_points)
return (len(conflict_points) > 0), conflict_points
def find_nearest_task_queue(agv_pos, task_queues, pickup_locks, start_points): """ 查找最近的未锁定任务队列 Args: agv_pos (tuple): AGV当前位置 (x, y) task_queues (dict): 任务队列字典 pickup_locks (dict): 取货点锁定状态字典 start_points (dict): 起始点坐标字典 Returns: str/None: 最近的未锁定取货点名称,如果没有则返回None """ candidates = [] for sp in task_queues: if task_queues[sp] and not pickup_locks[sp]: dist = manhattan(agv_pos, start_points[sp]) candidates.append((dist, sp)) if not candidates: return None return sorted(candidates, key=lambda x: x[0])[0][1]
mcp = FastMCP("PathServer")
def calculatePath(agv_position: str, agv_task: str) -> str: """ 计算AGV路径的主要函数 Args: agv_position (str): AGV位置数据文件路径 agv_task (str): AGV任务数据文件路径 Returns: str: 生成的CSV文件路径 """ def get_all_obstacles(): """ 获取所有障碍物位置(起始点和终点位置) Returns: set: 所有障碍物位置集合 """ return set(start_points.values()) | set(end_points.values())
def pso_task_assignment(free_agvs, available_tasks, agv_states, start_points): """使用PSO优化任务分配 Args: free_agvs (list): 空闲AGV列表 available_tasks (list): 可用任务列表 agv_states (dict): AGV状态字典 start_points (dict): 起始点坐标字典 Returns: list: 最优任务分配结果 """ n_agvs = len(free_agvs) n_tasks = len(available_tasks) if n_agvs == 0 or n_tasks == 0: return []
cost_matrix = np.zeros((n_tasks, n_agvs)) for i, task in enumerate(available_tasks): for j, agv_id in enumerate(free_agvs): sp = task['start_point'] start_pos = start_points[sp] agv_pos = agv_states[agv_id]['pos'] d = manhattan(agv_pos, start_pos) if task['priority'].lower() == 'urgent': d *= 0.5 cost_matrix[i, j] = d
def fitness_func(assignment): """ PSO适应度函数 Args: assignment (list): 任务分配方案 Returns: float: 适应度值(总成本) """ total_cost = 0 agv_count = np.zeros(n_agvs) for task_idx, agv_idx in enumerate(assignment): agv_idx = int(round(agv_idx)) if agv_idx < 0 or agv_idx >= n_agvs: return 1e9 agv_count[agv_idx] += 1 if agv_count[agv_idx] > 1: return 1e9 total_cost += cost_matrix[task_idx, agv_idx] return total_cost
dim = n_tasks lb = [0] * dim if n_agvs <= 1: ub = [1] * dim else: ub = [n_agvs - 1] * dim
pso = PSO(func=fitness_func, n_dim=dim, pop=min(50, n_tasks * n_agvs), max_iter=100, lb=lb, ub=ub, w=0.8, c1=0.5, c2=0.5)
pso.run() return np.round(pso.gbest_x).astype(int)
all_tasks = [] agv_position = os.path.join(os.getcwd(), agv_position) agv_task = os.path.join(os.getcwd(), agv_task)
with open(agv_task, 'r') as f: reader = csv.DictReader(f) for row in reader: all_tasks.append({ "task_id": row["task_id"], "start_point": row["start_point"].strip(), "end_point": row["end_point"].strip(), "priority": row["priority"], "remaining_time": int(row["remaining_time"]) if row["remaining_time"] not in [None, "", "None"] else None })
start_points, end_points, agv_list = {}, {}, [] with open(agv_position, 'r') as f: reader = csv.DictReader(f) for row in reader: t, name = row["type"].strip(), row["name"].strip() x, y = int(row["x"]), int(row["y"]) if t == "start_point": start_points[name] = (x, y) elif t == "end_point": end_points[name] = (x, y) elif t == "agv": agv_list.append({ "id": name, "pose": (x, y), "pitch": int(row["pitch"]) })
init_csv(agv_list)
task_queues = {} task_sequence = {} for task in all_tasks: sp = task["start_point"] if sp not in task_queues: task_queues[sp] = [] task_sequence[sp] = [] task_queues[sp].append(task) task_sequence[sp].append(task["task_id"])
agv_queue = [agv["id"] for agv in agv_list] agv_states = { agv["id"]: { "pos": tuple(agv["pose"]), "pitch": agv["pitch"], "time": 1, "home": tuple(agv["pose"]) } for agv in agv_list }
retain_count = 12 agv_queue = agv_queue[:retain_count]
reservation_table = {} assigned_tasks = []
pickup_locks = {sp: False for sp in task_queues} pickup_release_time = {sp: -1 for sp in task_queues} global_time = 1
while any(len(task_queues[sp]) > 0 for sp in task_queues) and global_time <= 300: for sp in pickup_locks: if pickup_locks[sp] and global_time > pickup_release_time[sp]: pickup_locks[sp] = False
agv_queue.sort(key=lambda aid: agv_states[aid]["time"]) agv_progress = {aid: False for aid in agv_queue}
free_agvs = [agv for agv in agv_queue if agv_states[agv]['time'] <= global_time] available_tasks = [] task_to_sp = {}
urgent_start_points_info = {} for sp in task_queues: queue = task_queues[sp] if queue and len(queue) > 0: for idx, task in enumerate(queue): if task['priority'].lower() == 'urgent': urgent_start_points_info[sp] = idx break
immediate_urgent_tasks = [] pso_normal_tasks = [] immediate_urgent_task_to_sp = {}
for sp in task_queues: queue = task_queues[sp] if queue and len(queue) > 0: first_task = queue[0] task_to_sp[first_task['task_id']] = sp
if sp in urgent_start_points_info: i = 0 urgent_index = urgent_start_points_info[sp] if i <= urgent_index: immediate_urgent_tasks.append(first_task) immediate_urgent_task_to_sp[first_task['task_id']] = sp i += 1 else: pso_normal_tasks.append(first_task) else: pso_normal_tasks.append(first_task)
if free_agvs and immediate_urgent_tasks: assigned_agv_set = set()
for task in immediate_urgent_tasks: sp = immediate_urgent_task_to_sp[task['task_id']] ep = task["end_point"] priority = task["priority"] emergency = True taskid = task["task_id"]
nearest_agv = None min_distance = float('inf') start_pos = start_points[sp]
for agv_id in free_agvs: if agv_id in assigned_agv_set: continue agv_pos = agv_states[agv_id]['pos'] distance = manhattan(agv_pos, start_pos) if distance < min_distance: min_distance = distance nearest_agv = agv_id
if nearest_agv: assigned_agv_set.add(nearest_agv)
start_coord = get_pickup_coord(sp, start_points[sp]) end_coord_main = end_points[ep] delivery_candidates = get_delivery_options(end_coord_main)
dynamic_obstacles = { agv_states[other_agv]["pos"] for other_agv in agv_queue if other_agv != nearest_agv and agv_states[other_agv]["time"] <= global_time + 40 }
path_to_pick = a_star(agv_states[nearest_agv]["pos"], start_coord, dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if path_to_pick: steps1, t1, pitch1, pos1 = simulate_path_strict_load( nearest_agv, path_to_pick, max(agv_states[nearest_agv]["time"], global_time), agv_states[nearest_agv]["pitch"], False, ep, emergency, taskid, sp, task_queues, pickup_release_time[sp] )
has_conflict, conflict_points = is_conflict(steps1, reservation_table) if has_conflict: path_to_pick = a_star(agv_states[nearest_agv]["pos"], start_coord, conflict_points | dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if path_to_pick: steps1, t1, pitch1, pos1 = simulate_path_strict_load( nearest_agv, path_to_pick, max(agv_states[nearest_agv]["time"], global_time), agv_states[nearest_agv]["pitch"], False, ep, emergency, taskid, sp, task_queues, pickup_release_time[sp] ) has_conflict, conflict_points = is_conflict(steps1, reservation_table)
if not has_conflict and path_to_pick: t1 += 1
best_steps2, best_t2, best_pitch2, best_pos2 = None, float("inf"), None, None for d in delivery_candidates: path_to_deliver = a_star(pos1, d, dynamic_obstacles | set(start_points.values()) | set( end_points.values())) if path_to_deliver: steps2, t2, pitch2, pos2 = simulate_path_strict_unload( nearest_agv, path_to_deliver, t1, pitch1, True, ep, emergency, taskid )
has_conflict, conflict_points = is_conflict(steps2, reservation_table) if has_conflict: path_to_deliver = a_star(pos1, d, conflict_points | dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if path_to_deliver: steps2, t2, pitch2, pos2 = simulate_path_strict_unload( nearest_agv, path_to_deliver, t1, pitch1, True, ep, emergency, taskid ) has_conflict, conflict_points = is_conflict(steps2, reservation_table)
if not has_conflict and path_to_deliver and best_t2 > t2: best_steps2, best_t2, best_pitch2, best_pos2 = steps2, t2, pitch2, pos2
if best_steps2: best_t2 += 1 full_steps = steps1 + best_steps2 reserve_simulated_steps(full_steps, reservation_table, nearest_agv) append_to_csv(full_steps)
assigned_tasks.append({ "agv": nearest_agv, "start_point": sp, "end_point": ep, "priority": priority, "start_time": max(agv_states[nearest_agv]["time"], global_time), "agv_start_pose": agv_states[nearest_agv]["pos"], "agv_start_orientation": agv_states[nearest_agv]["pitch"] })
agv_states[nearest_agv] = { "pos": best_pos2, "pitch": best_pitch2, "time": best_t2, "home": agv_states[nearest_agv]["home"] }
pickup_locks[sp] = True pickup_release_time[sp] = t1 task_queues[sp].pop(0) agv_progress[nearest_agv] = True
if nearest_agv in free_agvs: free_agvs.remove(nearest_agv)
if free_agvs and pso_normal_tasks: best_assignment = pso_task_assignment(free_agvs, pso_normal_tasks, agv_states, start_points) assigned_agv_set = set()
for i, agv_index in enumerate(best_assignment): if agv_index >= len(free_agvs): continue agv_id = free_agvs[agv_index] if agv_id in assigned_agv_set: continue assigned_agv_set.add(agv_id)
task = pso_normal_tasks[i] sp = task_to_sp[task['task_id']] ep = task["end_point"] priority = task["priority"] emergency = True if priority.lower() == "urgent" else False taskid = task["task_id"]
if not task_queues[sp] or task_queues[sp][0]["task_id"] != taskid: continue
start_coord = get_pickup_coord(sp, start_points[sp]) end_coord_main = end_points[ep] delivery_candidates = get_delivery_options(end_coord_main)
dynamic_obstacles = { agv_states[other_agv]["pos"] for other_agv in agv_queue if other_agv != agv_id and agv_states[other_agv]["time"] <= global_time + 40 }
path_to_pick = a_star(agv_states[agv_id]["pos"], start_coord, dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if not path_to_pick: continue
steps1, t1, pitch1, pos1 = simulate_path_strict_load( agv_id, path_to_pick, max(agv_states[agv_id]["time"], global_time), agv_states[agv_id]["pitch"], False, ep, emergency, taskid, sp, task_queues, pickup_release_time[sp] )
has_conflict, conflict_points = is_conflict(steps1, reservation_table) if has_conflict: path_to_pick = a_star(agv_states[agv_id]["pos"], start_coord, conflict_points | dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if not path_to_pick: continue steps1, t1, pitch1, pos1 = simulate_path_strict_load( agv_id, path_to_pick, max(agv_states[agv_id]["time"], global_time), agv_states[agv_id]["pitch"], False, ep, emergency, taskid, sp, task_queues, pickup_release_time[sp] ) has_conflict, conflict_points = is_conflict(steps1, reservation_table) if has_conflict: continue t1 += 1
best_steps2, best_t2, best_pitch2, best_pos2 = None, float("inf"), None, None for d in delivery_candidates: path_to_deliver = a_star(pos1, d, dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if not path_to_deliver: continue steps2, t2, pitch2, pos2 = simulate_path_strict_unload( agv_id, path_to_deliver, t1, pitch1, True, ep, emergency, taskid )
has_conflict, conflict_points = is_conflict(steps2, reservation_table) if has_conflict: path_to_deliver = a_star(pos1, d, conflict_points | dynamic_obstacles | set(start_points.values()) | set(end_points.values())) if not path_to_deliver: continue steps2, t2, pitch2, pos2 = simulate_path_strict_unload( agv_id, path_to_deliver, t1, pitch1, True, ep, emergency, taskid ) has_conflict, conflict_points = is_conflict(steps2, reservation_table) if has_conflict: continue if best_t2 > t2: best_steps2, best_t2, best_pitch2, best_pos2 = steps2, t2, pitch2, pos2
if not best_steps2: continue
best_t2 += 1 full_steps = steps1 + best_steps2 reserve_simulated_steps(full_steps, reservation_table, agv_id) append_to_csv(full_steps)
assigned_tasks.append({ "agv": agv_id, "start_point": sp, "end_point": ep, "priority": priority, "start_time": max(agv_states[agv_id]["time"], global_time), "agv_start_pose": agv_states[agv_id]["pos"], "agv_start_orientation": agv_states[agv_id]["pitch"] })
agv_states[agv_id] = { "pos": best_pos2, "pitch": best_pitch2, "time": best_t2, "home": agv_states[agv_id]["home"] }
pickup_locks[sp] = True pickup_release_time[sp] = t1 task_queues[sp].pop(0) agv_progress[agv_id] = True
if False in agv_progress.values(): for agv in agv_queue: state = agv_states[agv] if state["time"] <= global_time and not agv_progress[agv]: state["time"] += 1 idle_steps = [] idle_steps.append({ "timestamp": global_time, "name": agv, "X": state["pos"][0], "Y": state["pos"][1], "pitch": state["pitch"], "loaded": "false", "destination": "", "Emergency": "false", "task-id": "" }) if not any((step["timestamp"], (step["X"], step["Y"])) in reservation_table for step in idle_steps): reserve_simulated_steps(idle_steps, reservation_table, agv) append_to_csv(idle_steps)
if not any(agv_progress.values()): global_time += 1
final_time = max(state["time"] for state in agv_states.values())
finalize_trajectory_csv(agv_states, final_time) print(f"[INFO] 分配完成任务共计:{len(assigned_tasks)},总时长:{final_time} 秒") return CSV_PATH
def fill_idle_steps(start_time, end_time, agv_state, agv_name): """补足AGV在空闲期间的轨迹,确保轨迹完整 Args: start_time (int): 起始时间 end_time (int): 结束时间 agv_state (dict): AGV状态信息 agv_name (str): AGV名称 """ append_to_csv([{ "timestamp": start_time, "name": agv_name, "X": agv_state["pos"][0], "Y": agv_state["pos"][1], "pitch": agv_state["pitch"], "loaded": "false", "destination": "", "Emergency": "false", "task-id": "" }])
def to_lower_str(x): """ 将输入转换为小写字符串 Args: x (any): 输入值 Returns: str: 小写字符串或原值(如果为NaN) """ return str(x).lower() if pd.notna(x) else x
def finalize_trajectory_csv(agv_states, final_time, csv_path=CSV_PATH): """ 对所有 AGV 的轨迹进行时间补全并排序输出 Args: agv_states (dict): AGV状态字典 final_time (int): 最终时间 csv_path (str): CSV文件路径 """ with open(csv_path, 'a', newline='') as f: writer = csv.writer(f) for agv_id, state in agv_states.items(): last_time = state["time"] for t in range(last_time, final_time + 1): writer.writerow([ t, agv_id, state["pos"][0], state["pos"][1], state["pitch"], "false", "", "false", "" ])
col_names = pd.read_csv(csv_path, nrows=0).columns.tolist() df = pd.read_csv(csv_path, converters={col_names[5]: to_lower_str, col_names[7]: to_lower_str}) df.sort_values(by=["timestamp", "name"], inplace=True) df.to_csv(csv_path, index=False) print(f"[INFO] Final all AGV trajectory file with timestamp: saved to {csv_path}")
def detect_collisions(csv_path, output_path): """ 对最终输出的AGV轨迹CSV文件进行轨迹冲突判断 Args: csv_path (str): AGV轨迹CSV文件路径 output_path (str): 冲突记录输出文件路径 """ position_states = defaultdict(dict) agv_positions = defaultdict(dict)
with open(csv_path, 'r') as f: reader = csv.DictReader(f) for row in reader: timestamp = int(row['timestamp']) x, y = int(row['X']), int(row['Y']) agv = row['name'] position_states[timestamp][(x, y)] = agv agv_positions[agv][timestamp] = (x, y)
collisions = []
for timestamp in position_states: pos_counts = defaultdict(list) for pos, agv in position_states[timestamp].items(): pos_counts[pos].append(agv)
for pos, agvs in pos_counts.items(): if len(agvs) > 1: collisions.append({ "timestamp": timestamp, "X": pos[0], "Y": pos[1], "type": "static", "AGVs": ", ".join(agvs) })
seen_crossings = set() for agv1 in agv_positions: for agv2 in agv_positions: if agv1 >= agv2: continue for t in agv_positions[agv1]: if (t + 1 not in agv_positions[agv1]) or (t + 1 not in agv_positions[agv2]): continue
p1_now = agv_positions[agv1][t] p1_next = agv_positions[agv1][t + 1] p2_now = agv_positions[agv2][t] p2_next = agv_positions[agv2][t + 1]
if p1_now == p2_next and p2_now == p1_next: key = (t, tuple(sorted([agv1, agv2]))) if key not in seen_crossings: seen_crossings.add(key) collisions.append({ "timestamp": t, "X": p1_now[0], "Y": p1_now[1], "type": "crossing", "AGVs": f"{agv1}, {agv2}" })
print(">>>>>>>>Collision record start:") with open(output_path, 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=["timestamp", "X", "Y", "type", "AGVs"]) writer.writeheader() writer.writerows(collisions) print(collisions) print(">>>>>>>>Collision record end.")
print(f"[INFO] Detected {len(collisions)} collision events. Saved to {output_path}")
if __name__ == "__main__": print("开始路径规划...") calculatePath("map_data.csv", "task_data.csv")
print("开始评分计算...") from local_score import Score
score = Score() score.score_tasks()
print("任务完成!")
|