【问题标题】:Calculation of geometrical center from the set of XYZ coordinates从一组 XYZ 坐标计算几何中心
【发布时间】:2020-12-04 19:46:06
【问题描述】:

我有一组由 31 个原子组成的分子的 3D 坐标,存储在嵌套数组列表中:

[[121.133, 146.696, 139.126], [121.207, 145.489, 138.437], [122.058, 145.337, 137.335], [121.972, 143.689, 136.593], [123.209, 143.616, 135.31], [124.536, 143.881, 135.697], [124.87, 145.234, 135.928], [126.179, 145.569, 136.301], [127.156, 144.591, 136.455], [126.838, 143.258, 136.229], [123.824, 146.34, 135.736], [125.543, 142.913, 135.853], [123.008, 142.449, 134.454], [120.662, 143.598, 135.938], [122.362, 142.722, 137.625], [122.857, 146.427, 136.913], [122.764, 147.633, 137.625], [121.914, 147.77, 138.718], [123.101, 146.373, 134.374], [122.534, 147.208, 134.333], [122.482, 145.576, 134.33], [124.016, 146.346, 133.138], [125.066, 147.46, 133.272], [124.449, 148.847, 133.177], [123.972, 149.313, 131.947], [123.409, 150.582, 131.856], [123.322, 151.385, 132.993], [123.796, 150.925, 134.221], [124.36, 149.655, 134.314], [122.769, 152.634, 132.905], [123.339, 153.323, 133.255]]

所以每个子列表由每个原子的 XYZ 坐标组成,总共有 31 个子列表对应于每个原子。我需要使用这组坐标作为输入来计算这个分子的几何中心,从而产生一个 X Y Z 的点。

是否可以使用 numpy.mean 或其他标准 python 库来做到这一点?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    当然。只需使用

    import numpy as np
    
    def center(nested_array_list):
        a = np.array(nested_array_list)
        mean = np.mean(a, axis=0)
        return mean[0], mean[1], mean[2]  # x, y, z
    

    【讨论】:

    • 只有一个问题:如何在生成的 numpy 数组中设置浮点数?目前它给了我类似 (124.24238709677419, 146.01383870967749, 134.21829032258063) 的东西,而我只需要在 . ?
    • 对于printing,可以使用np.set_printoptions -> np.set_printoptions(precision=3),否则可以调用np.around(mean, decimals=3)
    • 所以我定义了 meann = numpy.around(mean, decimals=3) 然后返回 meann[0], meann[1], meann[2]。最终它为 y 和 z 打印 OK,但 x 仍然有很多数字:(123.50700000000001, 146.672, 135.303)
    • 那是因为floating point number representation。您看到的是最接近123.507 的数字,可以用python 浮点格式的位表示。要确保在小数点后准确打印三个字符,您可以print("xyz = [%.3f, %.3f, %.3f]" % tuple(mean))
    • 抱歉这个问题,这个打印语句应该在函数内部还是外部?是否可以将其存储在变量中?因为在脚本中我使用这些值将它们从列表转换为字符串格式
    【解决方案2】:

    其他标准 python 库

    您可以使用内置的statistics 模块来做到这一点。考虑以下玩具示例:

    import statistics
    points = [[10,20,30],[90,40,60]]
    center = [statistics.mean(i) for i in zip(*points)]
    print(center)  # [50, 30, 45]
    

    我使用zip 结合解包 (*) 来转置点,从而生成包含三个元组的列表,它们分别保存点 X 坐标、点 Y 坐标、点 Z 坐标。然后我通过所谓的列表理解在每个元组上使用了statistics.mean 函数。

    【讨论】:

      猜你喜欢
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多