Skip to content

Instantly share code, notes, and snippets.

@SqrtRyan
Created April 18, 2020 11:04
Show Gist options
  • Select an option

  • Save SqrtRyan/f2b8b01eeb71353f13c936bcc2208335 to your computer and use it in GitHub Desktop.

Select an option

Save SqrtRyan/f2b8b01eeb71353f13c936bcc2208335 to your computer and use it in GitHub Desktop.
#To run this code, please use "pip3 install rp matplotlib numpy"
n=2#Find the nth smallest edge out of N points
N=4
while True:
from rp import *
points=random_floats_complex(N)
points=as_points_array(points)
points=list(map(tuple,points))
from scipy.spatial import Delaunay
d=Delaunay(points)
edges=[]
edges+=d.simplices[:,[0,1]].tolist()
edges+=d.simplices[:,[0,2]].tolist()
edges+=d.simplices[:,[1,2]].tolist()
edges+=d.simplices[:,[1,0]].tolist()
edges+=d.simplices[:,[2,0]].tolist()
edges+=d.simplices[:,[2,1]].tolist()
edges=set(map(tuple,edges))
unique_edges={(x,y) for x,y in edges if x<=y} #Remove duplicate edges where (a,b) is the same as (b,a)
edges={tuple(points[i] for i in (x,y)) for x,y in edges}
point_pairs=sorted(combinations(points,2),key=lambda pair:euclidean_distance(*pair))#All possible edges sorted by distance. First is the closest point pair, second is second closest, etc...
if point_pairs[n] not in edges:
break
##
display_clear()
scatter_plot(points,dot_size=30)
for edge in edges:
display_path(as_numpy_array(edge),color='blue',alpha=.1)
def display_edge_length(*edge,color='blue'):
import matplotlib.pyplot as plt
edge=as_numpy_array(detuple(edge))
pos=(edge[0]+edge[1])/2
plt.text(pos[0],pos[1],str(euclidean_distance(edge[0],edge[1]))[:4],alpha=.5,color=color)
for edge in unique_edges:
display_edge_length(points[edge[0]],points[edge[1]])
nth_smallest_edge=as_numpy_array(point_pairs[n])
display_edge_length(nth_smallest_edge,color='red')
display_path(as_numpy_array(point_pairs[2]),color='red')
display_update(time=.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment