2016-07-05 20 views
7

Sorun:Optimize Dizi Eleman Vites değiştirirken Python/Numpy

yazdım bir veri analizi kod satırı profil çalıştırdıktan sonra, ben toplam çalışma süresinin% 70 civarında yapılan çağrılar yoğunlaşmaktadır bulduk iki farklı dizi manipülasyon rutinleri. Sonunda verileri gerçek zamanlı bir şekilde analiz etmek isterim, bu nedenle burada herhangi bir optimizasyon önemli ölçüde yardımcı olacaktır.

Matrix Forms

iki işlevi sol matris almak ve doğru (ve tam tersi) formuna getirmek.

İlgilendiğim matrisler şu anda N 2d numpy dizileriyle N olarak depolanır (burada N eşittir).

Kodu: Bunu başarmak için aşağıdaki kodu yazdım

: başlangıçta bu yazarken ben numpy en rulo fonksiyonunun farkında değildi, o yüzden içeri vec_shift fonksiyonlarını yazmıştı

# Shifts elements of a vector to the left by the given amount. 
def Vec_shift_L(vec, shift=0): 
    s = vec.size 
    out = np.zeros(s, dtype=complex) 
    out[:s-shift] = vec[shift:] 
    out[s-shift:] = vec[:shift] 
    return out 

# Shifts elements of a vector to the right by the given amount. 
def Vec_shift_R(vec,shift=0): 
    s=vec.size 
    out=np.zeros(s, dtype=complex) 
    out[:shift] = vec[s-shift:] 
    out[shift:] = vec[:s-shift] 
    return out 

# Shifts a matrix from the left form (above) to the right form. 
def OP_Shift(Trace): 
    s = Trace.shape 
    Out = np.zeros(s, dtype=complex) 

    for i in np.arange(s[0]): 
     Out[i,:] = Vec_shift_L(Trace[i,:], (i+s[0]/2) % s[0]) 

    for i in np.arange(s[0]): 
     Out[i,:] = np.flipud(Out[i,:]) 

    return Out 

# Shifts a matrix from the right form (above) to the left form. 
def iOP_Shift(Trace): 
    s = Trace.shape 
    Out = np.zeros(s, dtype=complex) 
    for i in np.arange(s[0]): 
     Out[i,:] = np.flipud(Trace[i,:]) 

    for i in np.arange(s[0]): 
     Out[i,:] = Vec_shift_R(Out[i,:], (i+s[0]/2) % s[0]) 

    return Out 

onun yer. Mevcut sistemimde roll kullanmanın% 30 üzerinde bir performans artışı var gibi görünüyor.

Bu kodun performansını daha da arttırmanın bir yolu var mı?

cevap

5

NumPy broadcasting, vektörel bir çözüm için size yardımcı olsun!

# Store shape of input array 
s = Trace.shape 

# Store arrays corresponding to row and column indices 
I = np.arange(s[0]) 
J = np.arange(s[1]-1,-1,-1) 

# Store all iterating values in "(i+s[0]/2) % s[0]" as an array 
shifts = (I + s[0]/2)%s[0] 

# Calculate all 2D linear indices corresponding to 2D transformed array 
linear_idx = (((shifts[:,None] + J)%s[1]) + I[:,None]*s[1]) 

# Finally index into input array with indices for final output 
out = np.take(Trace,linear_idx) 
+0

Teşekkürler! Uyumsuz matris şekilleri üzerinde bu tür şık bir şekilde işlem yapabildiğinizin farkında değildim. Bu önemli ölçüde yardımcı olur. : D – DMilden