Home > Mobile >  Generating repeating structures in graphs
Generating repeating structures in graphs

Time:07-10

How can I generate repeating structures like below? As can be seen, there is a 2d grid with with two diagonals (vertices 1,3,6,4 to name one) connected that is repeating.

enter image description here

CodePudding user response:

This is a possible solution. You just need to set the N parameter to whatever you want. In your first example you need N = 2, in the second example you need N = 3.

import networkx as nx

N = 3

G = nx.Graph()
for u in range(2 * N * (N   1)):
    if u % (2 * N   1) < N:
        for v in (u - 2 * N - 1, u - N - 1, u - N):
            if G.has_node(v):
                G.add_edge(u, v)
    elif u % (2 * N   1) == N:
        G.add_edge(u, u - N)
    elif u % (2 * N   1) < 2 * N:
        for v in (u - 1, u - N - 1, u - N):
            G.add_edge(u, v)
    else:
        for v in (u - 1, u - N - 1):
            G.add_edge(u, v)

Here is the output (for N = 2):

>>> G.nodes
NodeView((2, 0, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11))
>>> G.edges
EdgeView([(2, 0), (2, 3), (2, 5), (0, 3), (0, 5), (3, 1),
          (3, 4), (3, 5), (3, 6), (1, 4), (1, 6), (4, 6),
          (5, 7), (5, 8), (5, 10), (6, 8), (6, 9), (6, 11),
          (7, 8), (7, 10), (8, 9), (8, 10), (8, 11), (9, 11)])

If you want to get the adjacency matrix of the graph:

>>> nx.adjacency_matrix(G).todense()
  • Related