其他分享
首页 > 其他分享> > 将晶格转换为图?

将晶格转换为图?

作者:互联网

假设我有一个点距为d乘以Z的点的点阵,那么当且仅当这些点相邻时,如何才能有效地将其转换为图,其中节点为点,两点之间为边?

例如:假设我们在整数平方中得到的点对应于一个正方形的顶点…
我们如何将其转换为条目数为1或0的4×4矩阵(或图形),是否存在连接两个节点的边(对应于整数平方的点)

该示例很简单,有两个原因:

>这些点位于R平方中,因此输入是2维数组(其中输入通常是d维数组; d> 1
>多数点以明显的方式相连…但是这种模式(至少我发现)在d维度上变得不那么明显,每根轴上都有更多点….(如果我们取8点,这一点甚至很明显躺在立方体的边缘).

我正在寻找一种代码,该代码可以在给定任何此类数组(作为输入)的情况下实现此功能,并输出一个(表示必须对称的)矩阵,表示图上节点之间的边缘.

我用R编程(并愿意学习Python).

附言:我为这种奇怪的语法表示歉意…这种交换显然与LaTeX不兼容…:0

解决方法:

可以像这样在Python中实现:

from itertools import product

def print_lattice_edges(lattice):
    """prints all edges of a lattice, given as a list of lists of coordinates"""
    for idim, dim_coords in enumerate(lattice):
        for other_coords in product(*lattice[:idim] + lattice[idim+1:]):
            for coord1, coord2 in zip(dim_coords[:-1], dim_coords[1:]):
                edge1 = other_coords[:idim] + (coord1,) + other_coords[idim:]
                edge2 = other_coords[:idim] + (coord2,) + other_coords[idim:]
                print edge1, '->', edge2

说明:

>首先遍历所有尺寸,选择该尺寸的所有坐标
>通过删除选定的尺寸来创建新的晶格,并使用itertools.product遍历Cartesian product其余尺寸的所有可能坐标组合
>对于选定的尺寸,遍历所有可能的连续坐标对.
>通过将选定尺寸的坐标放回正确位置的笛卡尔乘积中,生成边缘的两个坐标.

如果您的应用程序涉及数百万个点并且速度是一个问题,则可以通过使用numpy生成笛卡尔乘积来执行类似的操作.

一些快速测试:

In [23]: print_lattice_edges([[0, 1], [0, 1]])  # your example
(0, 0) -> (1, 0)
(0, 1) -> (1, 1)
(0, 0) -> (0, 1)
(1, 0) -> (1, 1)

In [24]: print_lattice_edges([[0, 1], [3, 4, 5]])  # 2x3 points, 7 edges
(0, 3) -> (1, 3)
(0, 4) -> (1, 4)
(0, 5) -> (1, 5)
(0, 3) -> (0, 4)
(0, 4) -> (0, 5)
(1, 3) -> (1, 4)
(1, 4) -> (1, 5)

In [25]: print_lattice_edges([[0, 1], [0, 1], [0, 1]])  # cube, 12 edges
(0, 0, 0) -> (1, 0, 0)
(0, 0, 1) -> (1, 0, 1)
(0, 1, 0) -> (1, 1, 0)
(0, 1, 1) -> (1, 1, 1)
(0, 0, 0) -> (0, 1, 0)
(0, 0, 1) -> (0, 1, 1)
(1, 0, 0) -> (1, 1, 0)
(1, 0, 1) -> (1, 1, 1)
(0, 0, 0) -> (0, 0, 1)
(0, 1, 0) -> (0, 1, 1)
(1, 0, 0) -> (1, 0, 1)
(1, 1, 0) -> (1, 1, 1)

标签:matrix,graph,python,r
来源: https://codeday.me/bug/20191119/2032573.html