Statistics
| Branch: | Revision:

## mobicen / util / UnitDiskGraph.py @ 27b1b922

 1 ```# https://stackoverflow.com/questions/32424604/find-all-nearest-neighbors-within-a-specific-distance ``` ```import networkx as nx ``` ```from scipy.spatial import KDTree ``` ```from scipy.spatial.distance import cdist ``` ```import code # code.interact(local=dict(globals(), **locals())) ``` ```import graph_tool as gt ``` ```class UnitDiskGraph: ``` ``` def __init__(self, points, radius): ``` ``` self.G = nx.Graph() ``` ``` #self.G.add_nodes_from(range(len(points))) ``` ``` ``` ``` self.G = gt.Graph(directed=False) ``` ``` self.G.add_vertex(len(points)) ``` ``` self.edge_weights = self.G.new_edge_property('float') ``` ``` #self.G.edge_properties['weight'] = self.edge_weights ``` ``` ``` ``` self.generateGraphCDIST(points, radius) ``` ``` ``` ``` ``` ``` def genereateGraphFromKDtree(self, points, radius): ``` ``` tree = KDTree(points) ``` ``` edges = tree.query_pairs(r=radius) ``` ``` #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: ``` ``` edges.append([r,c, 1.0]) ``` ``` #self.G.add_weighted_edges_from(edges, weight='weight') ``` ``` #code.interact(local=dict(globals(), **locals())) ``` ``` self.G.ep["weight"] = self.G.new_edge_property("float") ``` ``` eprops = [self.G.ep["weight"]] ``` ``` self.G.add_edge_list(edges, hashed=True, eprops=eprops) ``` ``` #self.G.add_edge_list(edges, eprops=self.edge_weights) ``` ``` '''for e in edges: ``` ``` e = self.G.add_edge(e[0],e[1]) ``` ``` self.edge_weights[e] = 1.0''' ``` ``` def getGraph(self): ``` ``` return self.G ```