Cut_Line_Algorithm.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # 从文件读取一组节点
  2. nodes = []
  3. with open(r"C:\TSP\CDR_TO_TSP", "r") as file:
  4. nodes = file.readlines()
  5. # 删除第一个元素(源数据总数)
  6. nodes = nodes[1:]
  7. # 删除最后一个元素 换行(\n)
  8. nodes = nodes[:-1]
  9. # 定义一个函数来对节点进行排序和删除重复
  10. def sort_and_remove_duplicates(nodes):
  11. sorted_nodes = sorted(nodes) # 按照默认的元素顺序排序
  12. unique_nodes = [sorted_nodes[0]] # 保留第一个元素
  13. for node in sorted_nodes[1:]:
  14. # 如果当前节点与前一个节点不相同,则将其添加到列表中
  15. if node != unique_nodes[-1]:
  16. unique_nodes.append(node)
  17. return unique_nodes
  18. # 对节点进行排序和删除重复,写回文件
  19. unique_nodes = sort_and_remove_duplicates(nodes)
  20. total = len(unique_nodes)
  21. points = []
  22. for i in range(total):
  23. pot = unique_nodes[i].split()
  24. node = float(pot[0]), float(pot[1])
  25. points.append(node)
  26. # print(points)
  27. # boundary 是一个四元组,表示这组点的边界
  28. x_min = min(point[0] for point in points)
  29. x_max = max(point[0] for point in points)
  30. y_min = min(point[1] for point in points)
  31. y_max = max(point[1] for point in points)
  32. boundary = (x_min, x_max, y_min, y_max)
  33. print(boundary)
  34. # near_boundary_points将会是一个列表,包含所有距离边界不超过1的点
  35. near_boundary_points = []
  36. for point in points:
  37. if (
  38. abs(point[0] - x_min) <= 1
  39. or abs(point[0] - x_max) <= 1
  40. or abs(point[1] - y_min) <= 1
  41. or abs(point[1] - y_max) <= 1
  42. ):
  43. near_boundary_points.append(point)
  44. # print(near_boundary_points)
  45. tuples_list = near_boundary_points
  46. # 对元组列表分别按第二个元素进行升序排序 再第一个元素进行升序排序
  47. sorted_tuples = sorted(tuples_list, key=lambda x: x[1])
  48. near_boundary_points = sorted(sorted_tuples, key=lambda x: x[0])
  49. # 输出排序后的元组列表
  50. # print(near_boundary_points)
  51. # 统计 x = x_min 的坐标点个数, 也就是求边界框左边 节点个数
  52. left_points = []
  53. top_points = []
  54. for x, y in near_boundary_points:
  55. if x == x_min:
  56. left_points.append((x, y))
  57. if y == y_max:
  58. top_points.append((x, y))
  59. left_points.reverse()
  60. print(left_points)
  61. print(top_points)
  62. # 把裁切线节点 写文件 TSP2.tx ,完成算法
  63. total = len(left_points) + len(top_points)
  64. f = open(r"C:\TSP\TSP2.txt", "w")
  65. line = "%d %d\n" % (total, total)
  66. f.write(line)
  67. ext = 3 # extend 延长线 3mm
  68. inverter = 1
  69. for x, y in left_points:
  70. if inverter == 1:
  71. line = "%f %f %f %f\n" % (x - ext, y, x_max + ext, y)
  72. else:
  73. line = "%f %f %f %f\n" % (x_max + ext, y, x - ext, y)
  74. f.write(line)
  75. inverter = (inverter + 1) % 2
  76. for x, y in top_points:
  77. if inverter == 1:
  78. line = "%f %f %f %f\n" % (x, y + ext, x, y_min - ext)
  79. else:
  80. line = "%f %f %f %f\n" % (x, y_min - ext, x, y + ext)
  81. f.write(line)
  82. inverter = (inverter + 1) % 2