Veloce NumPy cartesiano di coordinate sferiche conversione?
-
29-09-2019 - |
Domanda
Ho un array di 3 milioni di punti di dati da un accellerometer 3-axiz (XYZ), e voglio aggiungere 3 colonne alla matrice contenente le coordinate sferiche equivalenti (r, theta, phi). Il seguente codice funziona, ma sembra troppo lento. Come posso fare meglio?
import numpy as np
import math as m
def cart2sph(x,y,z):
XsqPlusYsq = x**2 + y**2
r = m.sqrt(XsqPlusYsq + z**2) # r
elev = m.atan2(z,m.sqrt(XsqPlusYsq)) # theta
az = m.atan2(y,x) # phi
return r, elev, az
def cart2sphA(pts):
return np.array([cart2sph(x,y,z) for x,y,z in pts])
def appendSpherical(xyz):
np.hstack((xyz, cart2sphA(xyz)))
Soluzione
Questo è simile a Justin Peel ' s risposta, ma utilizzando solo numpy
e approfittando della sua built-in vettorializzazione:
import numpy as np
def appendSpherical_np(xyz):
ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
xy = xyz[:,0]**2 + xyz[:,1]**2
ptsnew[:,3] = np.sqrt(xy + xyz[:,2]**2)
ptsnew[:,4] = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
#ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
ptsnew[:,5] = np.arctan2(xyz[:,1], xyz[:,0])
return ptsnew
Si noti che, come suggerito nei commenti, ho cambiato la definizione di angolo di elevazione dal funzione originale. Sulla mia macchina, il test con pts = np.random.rand(3000000, 3)
, il tempo è passato da 76 secondi a 3,3 secondi. Non ho Cython quindi non ero in grado di confrontare i tempi con questa soluzione.
Altri suggerimenti
Ecco un codice rapido Cython che ho scritto per questo:
cdef extern from "math.h":
long double sqrt(long double xx)
long double atan2(long double a, double b)
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.float64_t DTYPE_t
@cython.boundscheck(False)
@cython.wraparound(False)
def appendSpherical(np.ndarray[DTYPE_t,ndim=2] xyz):
cdef np.ndarray[DTYPE_t,ndim=2] pts = np.empty((xyz.shape[0],6))
cdef long double XsqPlusYsq
for i in xrange(xyz.shape[0]):
pts[i,0] = xyz[i,0]
pts[i,1] = xyz[i,1]
pts[i,2] = xyz[i,2]
XsqPlusYsq = xyz[i,0]**2 + xyz[i,1]**2
pts[i,3] = sqrt(XsqPlusYsq + xyz[i,2]**2)
pts[i,4] = atan2(xyz[i,2],sqrt(XsqPlusYsq))
pts[i,5] = atan2(xyz[i,1],xyz[i,0])
return pts
Ha preso il tempo verso il basso da 62,4 secondi a 1.22 secondi con 3.000.000 punti per me. Questo non è troppo malandato. Sono sicuro che ci sono alcuni altri miglioramenti che possono essere fatte.
! C'è un errore ancora in tutto il codice qui sopra .. e questo è un risultato superiore di Google .. TLDR: Ho testato questo con vpython, utilizzando atan2 per theta (elev) è sbagliato, l'uso acos! E 'corretto per phi (Azim). Consiglio la sympy1.0 acos funzione (non ha nemmeno lamenta acos (z / r) con r = 0).
http://mathworld.wolfram.com/SphericalCoordinates.html
Se convertiamo che al sistema di fisica (r, theta, phi) = (r, elev, azimuth) abbiamo:
r = sqrt(x*x + y*y + z*z)
phi = atan2(y,x)
theta = acos(z,r)
Non ottimizzato ma corretta ??strong> codice per sistema di fisica destrorso:
from sympy import *
def asCartesian(rthetaphi):
#takes list rthetaphi (single coord)
r = rthetaphi[0]
theta = rthetaphi[1]* pi/180 # to radian
phi = rthetaphi[2]* pi/180
x = r * sin( theta ) * cos( phi )
y = r * sin( theta ) * sin( phi )
z = r * cos( theta )
return [x,y,z]
def asSpherical(xyz):
#takes list xyz (single coord)
x = xyz[0]
y = xyz[1]
z = xyz[2]
r = sqrt(x*x + y*y + z*z)
theta = acos(z/r)*180/ pi #to degrees
phi = atan2(y,x)*180/ pi
return [r,theta,phi]
è possibile verificare da soli con una funzione come:
test = asCartesian(asSpherical([-2.13091326,-0.0058279,0.83697319]))
alcuni altri dati di test per alcuni quadranti:
[[ 0. 0. 0. ]
[-2.13091326 -0.0058279 0.83697319]
[ 1.82172775 1.15959835 1.09232283]
[ 1.47554111 -0.14483833 -1.80804324]
[-1.13940573 -1.45129967 -1.30132008]
[ 0.33530045 -1.47780466 1.6384716 ]
[-0.51094007 1.80408573 -2.12652707]]
Ho usato vpython in aggiunta a facilmente visualizzare vettori:
test = v.arrow(pos = (0,0,0), axis = vis_ori_ALA , shaftwidth=0.05, color=v.color.red)
Per completare le risposte precedenti, ecco un Numexpr implementazione (con una possibile fallback Numpy),
import numpy as np
from numpy import arctan2, sqrt
import numexpr as ne
def cart2sph(x,y,z, ceval=ne.evaluate):
""" x, y, z : ndarray coordinates
ceval: backend to use:
- eval : pure Numpy
- numexpr.evaluate: Numexpr """
azimuth = ceval('arctan2(y,x)')
xy2 = ceval('x**2 + y**2')
elevation = ceval('arctan2(z, sqrt(xy2))')
r = eval('sqrt(xy2 + z**2)')
return azimuth, elevation, r
Per grandi dimensioni di matrice, questo permette un fattore 2 velocità fino rispetto a puro un'implementazione Numpy, e sarebbe paragonabile alle velocità C o Cython. La soluzione NumPy presente (quando utilizzato con l'argomento ceval=eval
) è 25% più veloce della funzione appendSpherical_np
nella risposta @mtrw per le dimensioni grandi array
In [1]: xyz = np.random.rand(3000000,3)
...: x,y,z = xyz.T
In [2]: %timeit -n 1 appendSpherical_np(xyz)
1 loops, best of 3: 397 ms per loop
In [3]: %timeit -n 1 cart2sph(x,y,z, ceval=eval)
1 loops, best of 3: 280 ms per loop
In [4]: %timeit -n 1 cart2sph(x,y,z, ceval=ne.evaluate)
1 loops, best of 3: 145 ms per loop
anche se per dimensioni più piccole, appendSpherical_np
è effettivamente più veloce,
In [5]: xyz = np.random.rand(3000,3)
...: x,y,z = xyz.T
In [6]: %timeit -n 1 appendSpherical_np(xyz)
1 loops, best of 3: 206 µs per loop
In [7]: %timeit -n 1 cart2sph(x,y,z, ceval=eval)
1 loops, best of 3: 261 µs per loop
In [8]: %timeit -n 1 cart2sph(x,y,z, ceval=ne.evaluate)
1 loops, best of 3: 271 µs per loop