保存球面点数据的快速Python代码

2024-10-03 11:16:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些数据要保存在物体表面的坐标上球体。所以呢我得到3个坐标,半径和数据。我想把这些数据加到一个给定半径的球上的每个坐标上。但是代码很慢,你知道怎么更快吗?你知道吗

def Grid(x, y, z, r, data):
    global voxelGrid   
    phi = 0
        #set the surface here
        z += surfaceZ

        while phi <= (2*math.pi):
            eta = math.pi * 2 / 3
            while eta <= math.pi:
                xx = x + r * math.sin(eta) * math.cos(phi)
                yy = y + r * math.sin(eta) * math.sin(phi)
                zz = z + r * math.cos(eta)

                xx = int(round((xx)))
                yy = int(round((yy)))
                zz = int(round((zz)))
                voxelGrid[xx][yy][zz] += data

                eta += 1/10 * math.pi

            phi += 1/10 * math.pi

所以我的第一个想法,是做一个查找表,因为我得到的数据是这样的:我得到一个点X,Y,Z,而不是一些不同的半径和数据。不同x、y、z位置的半径始终相同,因此每次都将对相同的数字进行此计算:

r * math.sin(eta) * math.cos(phi)
r * math.sin(eta) * math.sin(phi)
r * math.cos(eta)

所以我试着做了一些查找表,但这只是使代码更慢(可能是因为我使用全局变量):

def Grid(x, y, z, RadiusIndex, data):
    global voxelGrid
    global Phi
    global Eta
    global XX
    global YY
    global ZZ
    etaIndex = 0
    phiIndex = 0

        z += surfaceZ

        while phiIndex < len(Phi):

            while etaIndex < len(Eta):


                xx = x + XX[RadiusIndex][etaIndex][phiIndex]
                yy = y + YY[RadiusIndex][etaIndex][phiIndex]
                zz = z + ZZ[RadiusIndex][etaIndex]

                xx = int(round((xx)))
                yy = int(round((yy)))
                zz = int(round((zz)))
                voxelGrid[xx][yy][zz] += data
                etaIndex += 1

            phiIndex += 1
            etaIndex = 0

我用一些小的测试数据和cProfile进行了测量:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.449    1.449 <string>:1(<module>)
        1    1.449    1.449    1.449    1.449 confutures.py:8(Grid)
        1    0.000    0.000    1.449    1.449 {built-in method builtins.exec}
      168    0.000    0.000    0.000    0.000 {built-in method math.cos}
      168    0.000    0.000    0.000    0.000 {built-in method math.sin}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

我真的不明白什么是:内置方法内置.exec 我认为我的主要问题是全球numpy阵列,有没有办法做得更好?你知道吗


Tags: 数据pimathsincosglobalinteta