Skip to content

Instantly share code, notes, and snippets.

@Mahdisadjadi
Created September 7, 2018 17:43
Show Gist options
  • Save Mahdisadjadi/9eacdb123f652f96bd36a22e529b4aac to your computer and use it in GitHub Desktop.
Save Mahdisadjadi/9eacdb123f652f96bd36a22e529b4aac to your computer and use it in GitHub Desktop.
Python functions to detect whether a spring network realization is feasible in 2D
def isFlipped(sites1, sites2, bonds):
"""
Check if neighbors of a vertex
have changed the cyclic order.
"""
def sortClockwiseAroundVertex(coordinates, root, neighbors):
'''
Sort the neighbors of a vertex,
such that the one with lowest index
appears first.
'''
dr = coordinates[neighbors] - coordinates[root]
angles = np.arctan2(dr[:,1], dr[:,0])*180/(np.pi)
negAngles = angles<0
angles[negAngles] += 360
sortedarg = np.argsort(angles)
rollCounter = np.argmin(sortedarg)
idx = np.roll(sortedarg,shift=len(sortedarg)-rollCounter)
return np.array(neighbors)[idx]
n1,n2 = len(sites1), len(sites2)
if n1 != n2:
return 'Two conformations should have the same number of vertices.'
N = n1
# build the graph for neighbor lookup
G = nx.Graph([b for b in bonds])
for root in range(N):
neighbors = list(G.neighbors(root))
sortIn1 = sortClockwiseAroundVertex(sites1, root, neighbors)
sortIn2 = sortClockwiseAroundVertex(sites2, root, neighbors)
if np.any(sortIn1 != sortIn2):
return False
return True
def isPhysical1(state1, state2, bonds):
"""
Check if vertices forming a triangle have
changed their cyclic order,
"""
def sortClockwisePolygon(coordinates, indices):
'''A set of coordinates'''
coordinates = coordinates[indices]
center = np.mean(coordinates,0)
arr = coordinates - center
angles = np.arctan2(arr[:,1], arr[:,0])*180/(np.pi)
negAngles = angles<0
angles[negAngles] += 360
sortedarg = np.argsort(angles)
rollCounter = np.argmin(sortedarg)
idx = np.roll(sortedarg,shift=len(sortedarg)-rollCounter)
return np.array(indices)[idx]
n1,n2 = len(state1), len(state2)
if n1 != n2:
return 'Two conformations should have the same number of vertices.'
n = n1
#tris = combinations(np.arange(n), r=3)
G=nx.Graph([b for b in bonds])
tris = [item for item in nx.find_cliques(G) if len(item)==3]
for i,tri in enumerate(tris):
s1 = sortClockwisePolygon(state1, list(tri))
s2 = sortClockwisePolygon(state2, list(tri))
if np.any(s1!=s2):
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment