Statistics
| Branch: | Revision:

## mobicen / util / UnitDiskGraph.py @ b6158841

1 2 3 e1cf8bea LoreBz ```# https://stackoverflow.com/questions/32424604/find-all-nearest-neighbors-within-a-specific-distance ``` ```import networkx as nx ``` 1ef4948a LoreBz ```from scipy.spatial import KDTree ``` ```from scipy.spatial.distance import cdist ``` ```import code # code.interact(local=dict(globals(), **locals())) ``` ```import graph_tool as gt ``` e1cf8bea LoreBz ```class UnitDiskGraph: ``` ``` def __init__(self, points, radius): ``` 2dbcade9 LoreBz ``` self.nxG = nx.Graph() ``` ``` self.nxG.add_nodes_from(range(len(points))) ``` 1ef4948a LoreBz ``` ``` 2dbcade9 LoreBz ``` self.gtG = gt.Graph(directed=False) ``` 23c7ab1e LoreBz ``` self.gtG.add_vertex(len(points)) ``` 2dbcade9 LoreBz ``` self.edge_weights = self.gtG.new_edge_property('float') ``` ``` self.gtG.edge_properties['weight'] = self.edge_weights ``` 1ef4948a LoreBz ``` self.generateGraphCDIST(points, radius) ``` ``` ``` ``` ``` e1cf8bea LoreBz ``` def genereateGraphFromKDtree(self, points, radius): ``` 1ef4948a LoreBz ``` tree = KDTree(points) ``` e1cf8bea LoreBz ``` edges = tree.query_pairs(r=radius) ``` 1ef4948a LoreBz ``` #edges = [e+(1.0,) for e in edges] ``` ``` #pos = {k:points[k] for k in range(0,len(points))} ``` ``` #self.G.add_weighted_edges_from(edges, weight='weight') ``` ``` for e in edges: ``` ``` e = self.G.add_edge(e[0],e[1]) ``` ``` self.edge_weights[e] = 1.0 ``` ``` def generateGraphCDIST(self, points, radius): ``` ``` distM = cdist(points, points, 'euclidean') ``` ``` edges = [] ``` ``` for r in range(len(points)): ``` ``` for c in range(len(points)): ``` ``` if r==c: ``` ``` continue ``` ``` if distM[r][c] <= radius: ``` 27b1b922 LoreBz ``` edges.append([r,c, 1.0]) ``` 2dbcade9 LoreBz ``` self.nxG.add_weighted_edges_from(edges, weight='weight') ``` ``` ``` ``` self.gtG.ep["weight"] = self.gtG.new_edge_property("float") ``` ``` eprops = [self.gtG.ep["weight"]] ``` 23c7ab1e LoreBz ``` self.gtG.add_edge_list(edges, eprops=eprops) ``` e1cf8bea LoreBz ``` def getGraph(self): ``` 2dbcade9 LoreBz ` return self.gtG, self.nxG`