Guest User

Untitled

a guest
Feb 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import json
  3. X = 0
  4. Y = 1
  5.  
  6. def scale(s, pt):
  7.  
  8. return s*pt[X], s*pt[Y]
  9.  
  10. def dist_squared(p1, p2):
  11.  
  12. return (p1[X] - p2[X])**2 + (p1[Y] - p2[Y])**2
  13.  
  14. def sub(p1, p2):
  15.  
  16. return p1[X] - p2[X], p1[Y] - p2[Y]
  17.  
  18. def add(p1, p2):
  19.  
  20. return p1[X] + p2[X], p1[Y] + p2[Y]
  21.  
  22. def dot(p1, p2):
  23.  
  24. return p1[X] * p2[X] + p1[Y] * p2[Y]
  25.  
  26. def dist_to_segment(begin, end, curr):
  27.  
  28. d2 = dist_squared(begin, end)
  29. if d2 == 0.0:
  30. return dist_squared(begin, curr)
  31.  
  32. diff = sub(end, begin)
  33. d2beg = sub(curr, begin)
  34.  
  35. t = min(1.0, max(0.0, dot(diff, d2beg) / d2))
  36.  
  37. return dist_squared(add(begin, scale(t, diff)), curr)
  38.  
  39. def ramerdouglas(line, dist):
  40.  
  41. if dist == 0.0:
  42. return line[:]
  43.  
  44. if len(line) < 3:
  45. return line
  46.  
  47. (begin, end) = (line[0], line[-1]) if line[0] != line[-1] else
  48. (line[0], line[-2])
  49.  
  50. pos = -1
  51. maxdist = -1.0
  52. l = len(line)
  53. for k in range(1,l):
  54. d2 = dist_to_segment(begin, end, line[k])
  55. if d2 > maxdist:
  56. maxdist = d2
  57. pos = k - 1
  58.  
  59. if maxdist < dist ** 2:
  60. return [begin, end]
  61.  
  62. return (ramerdouglas(line[:pos + 2], dist) +
  63. ramerdouglas(line[pos + 1:], dist)[1:])
  64.  
  65. def to_xy(line):
  66. x = []
  67. y = []
  68. for pt in line:
  69. xx, yy = pt
  70. x.append(xx)
  71. y.append(yy)
  72.  
  73. return (x, y)
  74.  
  75.  
  76. if __name__ == "__main__":
  77. coast = [
  78. ( 0.181271 , 10.571000 ),
  79. ( 0.153745 , 10.620156 ),
  80. ( 0.114973 , 10.653889 ),
  81. ( 0.103274 , 10.707756 ),
  82. ( 0.157914 , 10.761511 ),
  83. ( 0.146256 , 10.811522 ),
  84. ( 0.061935 , 10.867833 ),
  85. ( 0.000000 , 10.960167 ),
  86. ( 8.107109 , 6.288978 ),
  87. ( 7.948394 , 6.177867 ),
  88. ( 7.925720 , 5.983422 ),
  89. ( 7.857699 , 5.816756 ),
  90. ( 7.835026 , 5.788978 ),
  91. ( 7.857699 , 5.511200 ),
  92. ( 7.812352 , 7.400089 ),
  93. ( 7.812352 , 4.344533 ),
  94. ( 7.812352 , 2.177867 ),
  95. ( 8.084435 , 4.733422 ),
  96. ( 8.107109 , 4.622311 ),
  97. ( 7.857699 , 4.344533 ),
  98. ( 7.630963 , 4.261200 ),
  99. ( 7.540268 , 4.177867 ),
  100. ( 7.494921 , 4.150089 )]
  101.  
  102.  
  103. x, y = to_xy(coast)
  104.  
  105. cst = ramerdouglas(coast, 0.1)
  106. xx, yy = to_xy(cst)
  107. print(xx, yy)
  108.  
  109. plt.plot(x, y, "bo", xx, yy, "r^")
  110. plt.show()
  111.  
  112. plt.plot(x, y, "bo", xx, yy, "r^")
Add Comment
Please, Sign In to add comment