简体   繁体   中英

Numpy array comparison using nditer

The code below is giving me the correct answer, but only works when the arrays ( plan and meas ) are relatively small. When I try to run this over the arrays I actually need to compare (300x300 each), it takes forever (I don't know how long because I have been terminating it after 45 minutes.) I would like to only iterate over a range of array values around the index being evaluated ( p ). I tried to find documentation on the nditer flag 'ranged' but cannot find how to implement a specific range to iterate through.

p = np.nditer(plan, flags = ['multi_index','common_dtype'])
while not p.finished:
    gam_store = 100.0
    m = np.nditer(meas, flags = ['multi_index','common_dtype'])
    while not m.finished:
        dis_eval = np.sqrt(np.absolute(p.multi_index[0]-m.multi_index[0])**2 + np.absolute(p.multi_index[1]-m.multi_index[1])**2)           
        if dis_eval <= 6.0:
            a = (np.absolute(p[0] - m[0]) / maxdose) **2
            b = (dis_eval / gam_dist) **2
            gam_eval = np.sqrt(a + b)
            if gam_eval < gam_store:
                gam_store = gam_eval
        m.iternext()    
    gamma = np.insert(gamma, location, gam_store, 0)
    location = location + 1
    p.iternext()

If you only want to iterate through a small part of the array, I think (unless I am misunderstanding the question) that you should just create an nditer instance from a slice of the array.

Say you only want the array near (i,j) , then start with this:

w = 5    # half-size of the window around i, j
p = np.nditer(plan[i-w:i+w, j-w:j+w], flags=...)

This works because, say

a = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])

Then,

w = 1
i, j = 2,2
print a[i-w:i+w+1, j-w:j+w+1]
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM