2016-07-05 11 views
7

समस्या:अनुकूलन सरणी तत्व स्थानांतरण अजगर/Numpy

एक डेटा विश्लेषण कोड मैं लिखा है की एक पंक्ति की रूपरेखा चलाने के बाद, मैं ने पाया है कि कुल चालू अवधि का लगभग 70% के लिए कॉल में केंद्रित है दो अलग सरणी हेरफेर दिनचर्या। मैं अंततः रीयल-टाइम फैशन में डेटा का विश्लेषण करना चाहता हूं, इसलिए यहां कोई भी अनुकूलन महत्वपूर्ण रूप से मदद करेगा।

Matrix Forms

दो कार्यों बाईं तरफ मैट्रिक्स लेने के लिए और सही (और इसके विपरीत) पर प्रपत्र पर ले आएं।

जिन मैट्रिक्स में मुझे रूचि है, वे वर्तमान में एन 2 डी numpy arrays (जहां एन भी है) द्वारा एन के रूप में संग्रहीत हैं।

कोड:

मैं निम्नलिखित कोड यह पूरा करने के लिए लिखा है:

# 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 

मैं numpy के रोल समारोह से अनजान थे जब मूल रूप से इस लेखन, तो मैं में vec_shift कार्यों लिखा था अपने जगह। ऐसा लगता है कि मेरे वर्तमान सिस्टम पर रोल का उपयोग करने पर ~ 30% प्रदर्शन वृद्धि हुई है।

क्या इस कोड के प्रदर्शन को और बढ़ाने के लिए कोई तरीका है?

उत्तर

5

NumPy broadcasting वेक्टरकृत समाधान के लिए आपकी सहायता करें!

# 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

धन्यवाद! मुझे एहसास नहीं हुआ कि आप इस तरह के सुरुचिपूर्ण तरीके से अन्यथा असंगत मैट्रिक्स आकारों पर संचालन कर सकते हैं। यह काफी मदद करता है। : डी – DMilden

संबंधित मुद्दे