【问题标题】:A 3-D grid of regularly spaced points规则间隔点的 3-D 网格
【发布时间】:2013-08-17 14:50:31
【问题描述】:

我想创建一个包含规则间隔点网格的 3-D 坐标的列表,每个点都是一个 3 元素元组。我正在寻找有关最有效方法的建议。

例如,在 C++ 中,我简单地循环了三个嵌套循环,每个坐标一个。在 Matlab 中,我可能会使用 meshgrid 函数(它会在一个命令中完成)。我读过 Python 中的 meshgrid 和 mgrid,我还读到使用 numpy 的广播规则更有效。在我看来,将 zip 函数与 numpy 广播规则结合使用可能是最有效的方法,但 zip 似乎并没有在 numpy 中过载。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用ndindex:

    import numpy as np
    ind=np.ndindex(3,3,2)
    for i in ind:
        print(i)
    
    # (0, 0, 0)
    # (0, 0, 1)
    # (0, 1, 0)
    # (0, 1, 1)
    # (0, 2, 0)
    # (0, 2, 1)
    # (1, 0, 0)
    # (1, 0, 1)
    # (1, 1, 0)
    # (1, 1, 1)
    # (1, 2, 0)
    # (1, 2, 1)
    # (2, 0, 0)
    # (2, 0, 1)
    # (2, 1, 0)
    # (2, 1, 1)
    # (2, 2, 0)
    # (2, 2, 1)
    

    【讨论】:

      【解决方案2】:

      除了meshgrid 和mgrid,您可以使用ogrid,它是mgrid 的“稀疏”版本。也就是说,只填写值变化的维度。其他的只是广播。与非稀疏替代方案相比,这对大型网格使用的内存要少得多。

      例如:

      >>> import numpy as np
      >>> x, y = np.ogrid[-1:2, -2:3]
      >>> x
      array([[-1],
            [ 0],
            [ 1]])
      >>> y
      array([[-2, -1,  0,  1,  2]])
      >>> x**2 + y**2
      array([[5, 2, 1, 2, 5],
            [4, 1, 0, 1, 4],
            [5, 2, 1, 2, 5]])
      

      【讨论】:

        【解决方案3】:

        我会说使用meshgridmgrid,特别是如果您需要非整数坐标。我很惊讶 Numpy 的广播规则会更有效,因为 meshgrid 是专为您想要解决的问题而设计的。

        【讨论】:

        • 广播允许大网格使用更少的内存。有关更多信息,请参阅我关于使用 ogrid 的回答。
        • @rephorm:确实(+1 表示您的评论)。在过去的两年里,我确实学到了这一点。 :)
        【解决方案4】:

        对于多维(大于 2)网格,使用 numpy.lib.index_tricks.nd_grid,如下所示:

        import numpy
        grid = numpy.lib.index_tricks.nd_grid()
        g1 = grid[:3,:3,:3]
        g2 = grid[0:1:0.5, 0:1, 0:2]
        g3 = grid[0:1:3j, 0:1:2j, 0:2:2j]
        

        其中 g1 的 x 值为 [0,1,2] g2 的 x 值为 [0,.5], g3 的 x 值为 [0.0,0.5,1.0](定义步数而不是步数增量的 3j。有关更多详细信息,请参阅documentation

        【讨论】:

        • 你也可以只使用 numpy.mgrid,它只是 numpy.lib.index_tricks.nd_grid 的一个实例。
        【解决方案5】:

        这是一个类似于您的 C++ 解决方案的有效选项,我已将其用于完全相同的目的:

        import numpy, itertools, collections
        def grid(xmin, xmax, xstep, ymin, ymax, ystep, zmin, zmax, zstep):
            "return nested tuples of grid-sampled coordinates that include maxima"
            return collections.deque( itertools.product( 
                numpy.arange(xmin, xmax+xstep, xstep).tolist(),
                numpy.arange(ymin, ymax+ystep, ystep).tolist(),
                numpy.arange(zmin, zmax+zstep, zstep).tolist() ) )
        

        使用 a.tolist() 时性能最好(在我的测试中),如上所示,但您可以改用 a.flat 并删除 deque() 以获取将消耗内存的迭代器。当然,您也可以使用普通的旧 tuple() 或 list() 代替 deque() 以获得轻微的性能损失(再次,在我的测试中)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-20
          • 2011-04-21
          • 2013-06-26
          • 2018-03-19
          • 2021-05-08
          • 1970-01-01
          • 2013-03-13
          • 2014-03-08
          相关资源
          最近更新 更多