예제 #1
0
 def test_multidigraph_unweighted(self):
     # This is the twice-singly-linked directed cycle graph on six nodes.
     edges = list(pairwise(range(6), cyclic=True))
     G = nx.MultiDiGraph(2 * edges)
     H = nx.DiGraph(G)
     G_cells = nx.voronoi_cells(G, {0, 3})
     H_cells = nx.voronoi_cells(H, {0, 3})
     assert_equal(G_cells, H_cells)
예제 #2
0
 def test_multidigraph_unweighted(self):
     # This is the twice-singly-linked directed cycle graph on six nodes.
     edges = list(pairwise(range(6), cyclic=True))
     G = nx.MultiDiGraph(2 * edges)
     H = nx.DiGraph(G)
     G_cells = nx.voronoi_cells(G, {0, 3})
     H_cells = nx.voronoi_cells(H, {0, 3})
     assert G_cells == H_cells
예제 #3
0
    def test_multigraph_unweighted(self):
        """Tests that the Voronoi cells for a multigraph are the same as
        for a simple graph.

        """
        edges = [(0, 1), (1, 2), (2, 3)]
        G = nx.MultiGraph(2 * edges)
        H = nx.Graph(G)
        G_cells = nx.voronoi_cells(G, {0, 3})
        H_cells = nx.voronoi_cells(H, {0, 3})
        assert_equal(G_cells, H_cells)
예제 #4
0
    def test_multigraph_unweighted(self):
        """Tests that the Voronoi cells for a multigraph are the same as
        for a simple graph.

        """
        edges = [(0, 1), (1, 2), (2, 3)]
        G = nx.MultiGraph(2 * edges)
        H = nx.Graph(G)
        G_cells = nx.voronoi_cells(G, {0, 3})
        H_cells = nx.voronoi_cells(H, {0, 3})
        assert G_cells == H_cells
예제 #5
0
 def test_directed_weighted(self):
     edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 1), (2, 1, 1)]
     G = nx.DiGraph()
     G.add_weighted_edges_from(edges)
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0}, 3: {1, 2, 3}}
     assert expected == cells
예제 #6
0
    def build_superworld(world, new_size):
        p = int(
            math.log2(len(world))
        ) + 1  # 2^p is number of points along each dimention of the space
        hc = HilbertCurve(p, 2)
        node_seq_coords = [(hc.distance_from_coordinates(n[1]['coords']), n[0])
                           for n in world.nodes(data=True)]
        node_seq_coords.sort()
        chunks = np.array_split(node_seq_coords, new_size)
        center_nodes = [chunk[len(chunk) // 2][1] for chunk in chunks]
        node_mapping = nx.voronoi_cells(world, center_nodes)

        new_nodes = []
        i = 0
        for center_node in center_nodes:
            new_nodes.append((i, {"nodes": node_mapping[center_node]}))
            for n in node_mapping[center_node]:
                world.nodes[n]['supernode'] = i
            i += 1
        superworld = nx.Graph(
        )  # we always use graph to simplify training, for both world and superworld
        superworld.add_nodes_from(new_nodes)
        # we assume all areas are approximately the same size, so we add edges in superworld of the same length
        edges = set()
        for e in world.edges():
            n1 = world.nodes[e[0]]['supernode']
            n2 = world.nodes[e[1]]['supernode']
            if n1 != n2 and (n1, n2) not in edges:
                edges.add((n1, n2))
        superworld.add_edges_from(list(edges))

        return superworld
 def test_directed_weighted(self):
     edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 1), (2, 1, 1)]
     G = nx.DiGraph()
     G.add_weighted_edges_from(edges)
     cells = nx.voronoi_cells(G, set([0, 3]))
     expected = {0: set([0]), 3: set([1, 2, 3])}
     assert_equal(expected, cells)
예제 #8
0
def main():
    # generate a fresh DiGraph
    generatedigraph(G)

    # user inputs center nodes
    node = input("Please enter a center node, or press ENTER to quit: ")
    while (node != ""):
        center_nodes.append(int(node))
        node = input("Please enter a center node, or press ENTER to quit: ")

    # obtains the Voronoi cells
    cells = nx.voronoi_cells(G, center_nodes)
    partition = set(map(frozenset, cells.values()))
    cells_list = list(sorted(map(sorted, partition)))
    print(cells_list)

    # adds color corresponding to Voronoi cell
    for i in range(0, len(cells_list)):
        for j in range(0, len(cells_list[i])):
            color_map.append(cm.hsv(1 / (i + .5)))

    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G,
                           pos,
                           with_labels=True,
                           node_color=color_map,
                           edge_color='k',
                           node_size=200,
                           alpha=0.5)
    pylab.title('Voronoi cells', fontsize=15)
    pylab.show()
예제 #9
0
 def test_directed_weighted(self):
     edges = [(0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 1), (2, 1, 1)]
     G = nx.DiGraph()
     G.add_weighted_edges_from(edges)
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0}, 3: {1, 2, 3}}
     assert_equal(expected, cells)
예제 #10
0
 def test_multidigraph_weighted(self):
     edges = [(0, 1, 10), (0, 1, 10), (1, 2, 1), (2, 3, 1), (3, 2, 10),
              (3, 2, 1), (2, 1, 10), (2, 1, 1)]
     G = nx.MultiDiGraph()
     G.add_weighted_edges_from(edges)
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0}, 3: {1, 2, 3}}
     assert_equal(expected, cells)
예제 #11
0
    def test_isolates(self):
        """Tests that a graph with isolated nodes has all isolates in
        one block of the partition.

        """
        G = nx.empty_graph(5)
        cells = nx.voronoi_cells(G, {0, 2, 4})
        expected = {0: {0}, 2: {2}, 4: {4}, 'unreachable': {1, 3}}
        assert_equal(expected, cells)
예제 #12
0
    def test_isolates(self):
        """Tests that a graph with isolated nodes has all isolates in
        one block of the partition.

        """
        G = nx.empty_graph(5)
        cells = nx.voronoi_cells(G, {0, 2, 4})
        expected = {0: {0}, 2: {2}, 4: {4}, 'unreachable': {1, 3}}
        assert expected == cells
    def test_isolates(self):
        """Tests that a graph with isolated nodes has all isolates in
        one block of the partition.

        """
        G = nx.empty_graph(5)
        cells = nx.voronoi_cells(G, set([0, 2, 4]))
        expected = {0: set([0]), 2: set([2]), 4: set([4]), 'unreachable': set([1, 3])}
        assert_equal(expected, cells)
def get_partitions(S2Near,graph):
    """
    Get list of nodes mapped in the Voronoi cell of the substation. The Voronoi 
    cell is determined on the basis of shortest path distance from each node to
    the nearest node to the substation.
    Returns: dictionary of substations with list of nodes mapped to it as values
    """
    # Compute Voronoi cells with network distance 
    centers = list(S2Near.values())
    cells = nx.voronoi_cells(graph, centers, 'length')
    
    # Recompute Voronoi cells for larger primary networks
    centers = [c for c in centers if len(cells[c])>100]
    cells = nx.voronoi_cells(graph, centers, 'length')
    
    # Recompute S2Near and S2Node
    S2Near = {s:S2Near[s] for s in S2Near if S2Near[s] in centers}
    S2Node = {s:list(cells[S2Near[s]]) for s in S2Near}
    return S2Node
예제 #15
0
    def test_directed_inward(self):
        """Tests that reversing the graph gives the "inward" Voronoi
        partition.

        """
        # This is the singly-linked reverse directed cycle graph on six nodes.
        G = nx.DiGraph(pairwise(range(6), cyclic=True))
        G = G.reverse(copy=False)
        cells = nx.voronoi_cells(G, {0, 3})
        expected = {0: {0, 4, 5}, 3: {1, 2, 3}}
        assert expected == cells
    def test_directed_inward(self):
        """Tests that reversing the graph gives the "inward" Voronoi
        partition.

        """
        # This is the singly-linked reverse directed cycle graph on six nodes.
        G = nx.DiGraph(pairwise(range(6), cyclic=True))
        G = G.reverse(copy=False)
        cells = nx.voronoi_cells(G, set([0, 3]))
        expected = {0: set([0, 4, 5]), 3: set([1, 2, 3])}
        assert_equal(expected, cells)
예제 #17
0
    def test_directed_inward(self):
        """Tests that reversing the graph gives the "inward" Voronoi
        partition.

        """
        # This is the singly-linked reverse directed cycle graph on six nodes.
        G = nx.DiGraph(pairwise(range(6), cyclic=True))
        G = G.reverse(copy=False)
        cells = nx.voronoi_cells(G, {0, 3})
        expected = {0: {0, 4, 5}, 3: {1, 2, 3}}
        assert_equal(expected, cells)
 def voronoi_util(self, state):
     center_nodes = {state.pos, state.opponent_pos}
     cells = nx.voronoi_cells(state.graph, center_nodes)
     return (len(cells[state.pos]) - len(state.opponent_pos)) / len(
         state.graph.nodes)
예제 #19
0
def vornoi(graph, path, characters, center_nodes):
    g = createSubGraph(graph, path, characters)
    return nx.voronoi_cells(g, center_nodes)
 def test_undirected_unweighted(self):
     G = nx.cycle_graph(6)
     cells = nx.voronoi_cells(G, set([0, 3]))
     expected = {0: set([0, 1, 5]), 3: set([2, 3, 4])}
     assert_equal(expected, cells)
예제 #21
0
import pylab
import matplotlib.cm as cm
import networkx as nx

# Generates the nodes
G = nx.path_graph(40)
center_nodes = {0, 2, 27}
cells = nx.voronoi_cells(G, center_nodes)
partition = set(map(frozenset, cells.values()))
sorted(map(sorted, partition))
temp_list = list(map(sorted, partition))

color_map = []

A = nx.DiGraph()

ctr_node_list = list(center_nodes)

# for center_node in ctr_node_list:
#     A.add_node(center_node)
#     color_map.append('black')

# add nodes to the graph in corresponding colors
for i in range(0, len(center_nodes)):
    nodes = temp_list[i]
    for node in nodes:
        A.add_node(node)
        color_map.append(cm.hsv(1 / (i + .5)))

pos = nx.spring_layout(A)
nx.draw_networkx_nodes(A, pos, node_color=color_map, with_labels=True)
 def test_directed_unweighted(self):
     # This is the singly-linked directed cycle graph on six nodes.
     G = nx.DiGraph(pairwise(range(6), cyclic=True))
     cells = nx.voronoi_cells(G, set([0, 3]))
     expected = {0: set([0, 1, 2]), 3: set([3, 4, 5])}
     assert_equal(expected, cells)
    def fit_voronoi_cells_method(self):
        #not robust to graph with multiple connected components
        '''
        Purpose :
        _________    
            compute the kmeans of the graph G using the method specified in the constructor
        
        Ouput :
        _______    
            a dictionary final_d :Graph.Nodes()-> Set of all centers
                every node is assocaited to its closest center 
                
        Remarks:
        ________
            Usually faster than the explicit method, however, the input graph must be connected for the voronoi cells to be utilized.
            If the graph is disconnected, then use the other fitting method, fit_explicit_method, for computation.
        '''

        if nx.is_connected(self.G) == False:
            raise ValueError(
                "the input graph is disconnected. Use the method fit_explicit_method to fit the data instead."
            )

        # pick randomly k numbers from (0,len(G))
        nodes_k = random.sample(self.G.nodes(), self.k)

        current_centers = nodes_k

        # the output is a function that maps every node to the center index
        final_d = {}
        stable = 0
        cells = []
        for i in range(0, self.iters):
            print("Doing iteration " + str(i))
            # stage 1 : assigning each node to its closest center

            cells = nx.voronoi_cells(self.G, current_centers, weight='weight')
            '''
            For more inforamtion, check the refs: 
            
                
            (i) https://iopscience.iop.org/article/10.1088/1367-2630/16/6/063007/pdf?fbclid=IwAR0uCHUYqzdKhqp9DIOwZEMcUSxZs3h6ctT2WAEIYGw6p4SaNx-BqHXYOzA    
                
            (ii) Erwig, Martin. (2000), “The graph Voronoi diagram with applications.” Networks, 36: 156–163. <dx.doi.org/10.1002/1097-0037(200010)36:3<156::AID-NET2>3.0.CO;2-L>
            
            (iii) https://web.engr.oregonstate.edu/~erwig/papers/GraphVoronoi_Networks00.pdf?fbclid=IwAR0i1R4pfnfqwggBMlIfTc48WNl2ttFEbN2hkHim3F8E3RPUAVbbgm4MTLs      
            '''

            newcenters = []
            # stage 2 : updating the centers based on the previous step.

            for cell in cells.values():

                #1 define the graph with the previous nodes :

                subgraph = self.G.subgraph(cell)

                #2 compute the center of the subgraph after choosing the center update method
                #_____________________

                center = self.compute_subgraph_center(subgraph)

                newcenters.append(center)
            #stage 3 check for convergence
            if sorted(current_centers) == sorted(
                    newcenters
            ):  # centers are not changing for a certain number of iterations
                stable = stable + 1
                if stable == 3:
                    print("Algorithm converges with " + str(i) + " steps.")
                    break

            #stage 4 update the centers if we did not converge and get ready for the next loop
            current_centers = newcenters
        if stable != 3:  # TODO : better implementation needed
            print("Algorithm did not converge")

        for key, value in zip(cells.keys(), cells.values()):
            for v in value:
                final_d[v] = key

        self.final_dic = final_d

        print("Done!")
        return final_d
예제 #24
0
    'tag': list(pagerk.keys()),
    'pagerank': list(pagerk.values())
})
pagerkdf = pagerkdf.sort_values(by='pagerank', ascending=False)

import matplotlib.pyplot as plt
plt.figure()
plt.plot(
    np.linspace(pagerkdf['pagerank'].min(),
                pagerkdf['pagerank'].max(),
                num=len(pagerkdf)), pagerkdf['pagerank'].values)
#FOR APPLE after first 4, curve slows down badly. use first 4 as main nodes
#FOR ELL: after first 6, curve slows down badly. use first 6 as main nodes
cn = pagerkdf['tag'].iloc[:6].tolist()
vc = nx.voronoi_cells(
    G, center_nodes=cn
)  # keys are tags selected as topics page-rank, values are tags in each topic
pd.to_pickle(
    vc, out_dir + 'topicsFromTags.pkl'
)  # it doesn't look too good the allocation of tags to topics, but i still believe that is the most appropriate method
topics = pd.read_pickle(out_dir + 'topicsFromTags.pkl')

nodes = []
colors = []
ntopics = len(topics)
topic_names = list(topics.keys())
cmap = matplotlib.cm.get_cmap('Set2')
for i in range(ntopics):
    lists = topics[topic_names[i]]
    nodes.extend(list(lists))
    c = [cmap(i) for j in range(len(lists))]
예제 #25
0
 def test_directed_unweighted(self):
     # This is the singly-linked directed cycle graph on six nodes.
     G = nx.DiGraph(pairwise(range(6), cyclic=True))
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0, 1, 2}, 3: {3, 4, 5}}
     assert expected == cells
예제 #26
0
 def test_undirected_unweighted(self):
     G = nx.cycle_graph(6)
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0, 1, 5}, 3: {2, 3, 4}}
     assert expected == cells
예제 #27
0
 def test_undirected_unweighted(self):
     G = nx.cycle_graph(6)
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0, 1, 5}, 3: {2, 3, 4}}
     assert_equal(expected, cells)
예제 #28
0
 def test_directed_unweighted(self):
     # This is the singly-linked directed cycle graph on six nodes.
     G = nx.DiGraph(pairwise(range(6), cyclic=True))
     cells = nx.voronoi_cells(G, {0, 3})
     expected = {0: {0, 1, 2}, 3: {3, 4, 5}}
     assert_equal(expected, cells)