, -
def unq_localmin(A, dim):
m, n = A.shape
M4D = A.reshape(m//dim, dim, n//dim, dim)
M2Dr = M4D.swapaxes(1,2).reshape(-1,dim**2)
a = M2Dr.copy()
N = M2Dr.shape[0]
R = np.empty(N,dtype=int)
C = np.empty(N,dtype=int)
shp = M2Dr.shape
for i in range(N):
r,c = np.unravel_index(np.argmin(a),shp)
a[r] = np.inf
a[:,c] = np.inf
R[i], C[i] = r, c
out = M2Dr[R,C]
idr = np.column_stack(np.unravel_index(R,(dim,dim)))
idc = np.column_stack(np.unravel_index(C,(dim,dim)))
return zip(map(tuple,idr),map(tuple,idc),out)
9x9 / 3x3 OP get_mins -
In [66]: A # Input data array
Out[66]:
array([[ 927., 852., 18., 949., 933., 558., 519., 118., 82.],
[ 939., 782., 178., 987., 534., 981., 879., 895., 407.],
[ 968., 187., 539., 986., 506., 499., 529., 978., 567.],
[ 767., 272., 881., 858., 621., 301., 675., 151., 670.],
[ 874., 221., 72., 210., 273., 823., 784., 289., 425.],
[ 621., 510., 303., 935., 88., 970., 278., 125., 669.],
[ 702., 722., 620., 51., 845., 414., 154., 154., 635.],
[ 600., 928., 540., 462., 772., 487., 196., 499., 208.],
[ 654., 335., 258., 297., 649., 712., 292., 767., 819.]])
In [67]: unq_localmin(A, dim = 3) # Using proposed approach
Out[67]:
[((0, 0), (0, 2), 18.0),
((2, 1), (0, 0), 51.0),
((1, 0), (1, 2), 72.0),
((1, 1), (2, 1), 88.0),
((0, 2), (0, 1), 118.0),
((2, 2), (1, 0), 196.0),
((2, 0), (2, 2), 258.0),
((1, 2), (2, 0), 278.0),
((0, 1), (1, 1), 534.0)]
In [68]: out = np.empty((9,9))
In [69]: get_mins(out,A) # Using OP soln with dim = 3 edited
Out[69]:
[((0, 0), (0, 2), 18.0),
((2, 1), (0, 0), 51.0),
((1, 0), (1, 2), 72.0),
((1, 1), (2, 1), 88.0),
((0, 2), (0, 1), 118.0),
((2, 2), (1, 0), 196.0),
((2, 0), (2, 2), 258.0),
((1, 2), (2, 0), 278.0),
((0, 1), (1, 1), 534.0)]
, , get_mins. , , :
def unq_localmin_v2(A, dim):
m, n = A.shape
M4D = A.reshape(m
M2Dr = M4D.swapaxes(1,2).reshape(-1,dim**2)
N = M2Dr.shape[0]
out = np.empty(N)
shp = M2Dr.shape
for i in range(N):
r,c = np.unravel_index(np.argmin(M2Dr),shp)
out[i] = M2Dr[r,c]
M2Dr[r] = np.inf
M2Dr[:,c] = np.inf
return out
-
In [52]: A = np.random.randint(11,999,(9,9)).astype(float)
In [53]: %timeit unq_localmin_v2(A, dim=3)
10000 loops, best of 3: 93.1 µs per loop
In [54]: out = np.empty((9,9))
In [55]: %timeit get_mins(out,A)
1000 loops, best of 3: 907 µs per loop