【问题标题】:Networkx - Find individual hexagons in honeycomb structureNetworkx - 在蜂窝结构中查找单个六边形
【发布时间】:2021-08-19 19:07:33
【问题描述】:

我只是在研究这个类似蜂窝的结构网络,我是按照这个线程中接受的答案生成的:Hexagonal lattice in different layers by networkx

为方便起见,复制如下:

def node_dist(x,y, cx, cy):
    """Distance of each node from the center of the innermost layer"""
    return abs(cx-x) + abs(cy-y)


def remove_unwanted_nodes(G, m):
    """Remove all the nodes that don't belong to an m-layer hexagonal ring."""
    
    #Compute center of all the hexagonal rings as cx, cy
    cx, cy = m-0.5, 2*m -(m%2) #odd is 2m-1, even is 2m
    
    #in essence, we are converting from a rectangular grid to a hexagonal ring... based on distance.
    unwanted = []
    for n in G.nodes:    
        x,y = n
        #keep short distance nodes, add far away nodes to the list called unwanted
        if node_dist(x,y, cx, cy) > 2*m:
            unwanted.append(n)

    #now we are removing the nodes from the Graph
    for n in unwanted:
        G.remove_node(n)
        
    return G

m = 2 #change m here. 1 = 1 layer, single hexagon.
G = nx.hexagonal_lattice_graph(2*m-1,2*m-1, periodic=False, 
                               with_positions=True, 
                               create_using=None)
pos = nx.get_node_attributes(G, 'pos')
G = remove_unwanted_nodes(G, m)

#render the result
plt.figure(figsize=(4,4)) 
nx.draw(G, pos=pos, with_labels=True)
plt.axis('scaled')
plt.show()

这会产生这样的情节:

如何找到形成这个蜂窝的所有单独的六边形?

我尝试了循环、派系和锁链,但它们似乎都没有给我想要的答案……除非我做错了什么。

任何帮助将不胜感激!

【问题讨论】:

  • 不幸的是,您指定的循环没有任何好的图论属性。您最好的方法可能就是了解您的图表。查看十六进制中最左边的点说 (a, b) 其他点是 (a, b+1), (a, b-1), (a+1, b), (a+1, b+1 ) 和 (a+1, b-1)。

标签: python networkx


【解决方案1】:

我相信 nx.simple_cycles() 是您想要的,但如果您尝试在无向图上调用它,则会收到错误消息,指出此算法未针对此图类型实现。

以下方法不优雅,如果您需要它可能无法很好地扩展,但它达到了预期的结果。您可以将无向图转换为有向图,它只是用两条有向边替换所有无向边,每个方向一个。然后,您可以在其上调用nx.simple_cycles(),限制为长度为 6 的循环,并根据每个循环中存在的节点集对 6 循环进行重复数据删除:

DG = G.to_directed()
cycles = nx.simple_cycles(DG)
hex_cycles = [path for path in cycles if len(path) == 6]
hex_loops = []
for cycle in hex_cycles:
    if set(cycle) not in [set(loop) for loop in hex_loops]:
        hex_loops.append(cycle)

根据需要给出hex_loops

[[(3, 4), (2, 4), (2, 5), (2, 6), (3, 6), (3, 5)],
 [(3, 4), (2, 4), (2, 3), (2, 2), (3, 2), (3, 3)],
 [(0, 2), (1, 2), (1, 3), (1, 4), (0, 4), (0, 3)],
 [(0, 5), (0, 6), (1, 6), (1, 5), (1, 4), (0, 4)],
 [(2, 2), (2, 3), (1, 3), (1, 2), (1, 1), (2, 1)],
 [(2, 4), (2, 5), (1, 5), (1, 4), (1, 3), (2, 3)],
 [(2, 7), (1, 7), (1, 6), (1, 5), (2, 5), (2, 6)]]

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2015-03-13
    • 2021-05-17
    • 1970-01-01
    • 2011-12-04
    • 2022-01-14
    • 2018-10-06
    • 2014-08-21
    相关资源
    最近更新 更多