def find_peak(corr, method='gaussian'):
"""Peak detection algorithm switch
After loading the correlation window an maximum finder is invoked.
The correlation window is cut down to the necessary 9 points around the maximum.
Afterwards the maximum is checked not to be close to the boarder of the correlation frame.
This cropped window is used in along with the chosen method to interpolate the sub pixel shift.
Each interpolation method returns a tuple with the sub pixel shift in x and y direction.
The maximums position and the sub pixel shift are added and returned.
If an error occurred during the sub pixel interpolation the shift is set to nan.
Also if the interpolation method is unknown an exception in thrown.
:param corr: correlation window
:param method: peak finder algorithm (gaussian, centroid, parabolic, 9point)
:raises: Sub pixel interpolation method not found
:returns: shift in interrogation window
"""
i, j = np.unravel_index(corr.argmax(), corr.shape)
if check_peak_position(corr, i, j) is False:
return np.nan, np.nan
window = corr[i-1:i+2, j-1:j+2]
if method == 'gaussian':
subpixel_interpolation = gaussian
elif method == 'centroid':
subpixel_interpolation = centroid
elif method == 'parabolic':
subpixel_interpolation = parabolic
elif method == '9point':
subpixel_interpolation = gaussian2D
else:
raise Exception('Sub pixel interpolation method not found!')
try:
dx, dy = subpixel_interpolation(window)
except:
return np.nan, np.nan
else:
return (i + dx, j + dy)
python类unravel_index()的实例源码
def _sample_direct(self, rng, state, mode, n_samples, out, eps):
"""Sample from full pmfilities (call :func:`self.sample`)"""
pmf = self.pmf_as_array(state, mode, eps)
choices = rng.choice(pmf.size, n_samples, p=pmf.flat)
for pos, c in enumerate(np.unravel_index(choices, pmf.shape)):
out[:, pos] = c
def test_array_orientation_consistency_tilt():
''' The pupil array should be shaped as arr[x,y], as should the psf and MTF.
A linear phase error in the pupil along y should cause a motion of the
PSF in y. Specifically, for a positive-signed phase, that should cause
a shift in the +y direction.
'''
samples = 128
p = Seidel(W111=1, samples=samples)
ps = PSF.from_pupil(p, 1)
idx_y, idx_x = np.unravel_index(ps.data.argmax(), ps.data.shape) # row-major y, x
assert idx_x == ps.center_x
assert idx_y > ps.center_y
def nanargmax(a):
idx = np.argmax(a, axis=None)
multi_idx = np.unravel_index(idx, a.shape)
if np.isnan(a[multi_idx]):
nan_count = np.sum(np.isnan(a))
# In numpy < 1.8 use idx = np.argsort(a, axis=None)[-nan_count-1]
idx = np.argpartition(a, -nan_count-1, axis=None)[-nan_count-1]
multi_idx = np.unravel_index(idx, a.shape)
return multi_idx
def nanargmax(a):
idx = np.argmax(a, axis=None)
multi_idx = np.unravel_index(idx, a.shape)
if np.isnan(a[multi_idx]):
nan_count = np.sum(np.isnan(a))
# In numpy < 1.8 use idx = np.argsort(a, axis=None)[-nan_count-1]
idx = np.argpartition(a, -nan_count-1, axis=None)[-nan_count-1]
multi_idx = np.unravel_index(idx, a.shape)
return multi_idx
world_generator.py 文件源码
项目:Learning-to-navigate-without-a-map
作者: ToniRV
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def create_world_from_grid(self, grid, im_size, start, goal):
# Create gazebo world out of the grid
scale = 0.75
# Add start box
self.add_target_box_green(start[0], start[1])
# Add goal box
self.add_target_box_red(goal[0], goal[1])
# Build walls around the field
wall_width = 0.5
self.add_wall(scale*(im_size[0]-1)/2.0, 0, 0, scale*(im_size[0]-1), wall_width)
self.add_wall(0, scale*(im_size[1]-1)/2.0, pi / 2.0, scale*(im_size[0]-1), wall_width)
self.add_wall(scale*(im_size[0]-1), scale*(im_size[1]-1)/2.0, - pi / 2.0, scale*(im_size[0]-1), wall_width)
self.add_wall(scale*(im_size[0]-1)/2.0, scale*(im_size[1]-1), pi, scale*(im_size[0]-1), wall_width)
# Add asphalt
self.add_tarmac(scale*(im_size[0]-1)/2.0, scale*(im_size[1]-1)/2.0, 0, scale*(im_size[0]-1), scale*(im_size[1]-1))
# Add cones wherever there should be obstacles
i = 1
j = 1
obstacle_indices = np.where(grid != 1)
unraveled_indices = np.unravel_index(obstacle_indices, im_size, order='C')
for x in grid:
if (grid[j+i*im_size[0]] != 1):
self.add_cone(scale*j, scale*i)
self.write()
j += 1
if (j % (im_size[1]-1)) == 0:
j = 1
i +=1
if (i == im_size[0]-1):
break
def ind2sub(shape, inds):
"""From the given shape, returns the subscripts of the given index"""
if type(inds) is not np.ndarray:
inds = np.array(inds)
assert len(inds.shape) == 1, (
'Indexing must be done as a 1D row vector, e.g. [3,6,6,...]'
)
return np.unravel_index(inds, shape, order='F')
def test_basic(self):
assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2)
assert_equal(np.unravel_index(254, (17, 94)), (2, 66))
assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254)
assert_raises(ValueError, np.unravel_index, -1, (2, 2))
assert_raises(TypeError, np.unravel_index, 0.5, (2, 2))
assert_raises(ValueError, np.unravel_index, 4, (2, 2))
assert_raises(ValueError, np.ravel_multi_index, (-3, 1), (2, 2))
assert_raises(ValueError, np.ravel_multi_index, (2, 1), (2, 2))
assert_raises(ValueError, np.ravel_multi_index, (0, -3), (2, 2))
assert_raises(ValueError, np.ravel_multi_index, (0, 2), (2, 2))
assert_raises(TypeError, np.ravel_multi_index, (0.1, 0.), (2, 2))
assert_equal(np.unravel_index((2*3 + 1)*6 + 4, (4, 3, 6)), [2, 1, 4])
assert_equal(
np.ravel_multi_index([2, 1, 4], (4, 3, 6)), (2*3 + 1)*6 + 4)
arr = np.array([[3, 6, 6], [4, 5, 1]])
assert_equal(np.ravel_multi_index(arr, (7, 6)), [22, 41, 37])
assert_equal(
np.ravel_multi_index(arr, (7, 6), order='F'), [31, 41, 13])
assert_equal(
np.ravel_multi_index(arr, (4, 6), mode='clip'), [22, 23, 19])
assert_equal(np.ravel_multi_index(arr, (4, 4), mode=('clip', 'wrap')),
[12, 13, 13])
assert_equal(np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)), 1621)
assert_equal(np.unravel_index(np.array([22, 41, 37]), (7, 6)),
[[3, 6, 6], [4, 5, 1]])
assert_equal(
np.unravel_index(np.array([31, 41, 13]), (7, 6), order='F'),
[[3, 6, 6], [4, 5, 1]])
assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1])
def test_dtypes(self):
# Test with different data types
for dtype in [np.int16, np.uint16, np.int32,
np.uint32, np.int64, np.uint64]:
coords = np.array(
[[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype)
shape = (5, 8)
uncoords = 8*coords[0]+coords[1]
assert_equal(np.ravel_multi_index(coords, shape), uncoords)
assert_equal(coords, np.unravel_index(uncoords, shape))
uncoords = coords[0]+5*coords[1]
assert_equal(
np.ravel_multi_index(coords, shape, order='F'), uncoords)
assert_equal(coords, np.unravel_index(uncoords, shape, order='F'))
coords = np.array(
[[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]],
dtype=dtype)
shape = (5, 8, 10)
uncoords = 10*(8*coords[0]+coords[1])+coords[2]
assert_equal(np.ravel_multi_index(coords, shape), uncoords)
assert_equal(coords, np.unravel_index(uncoords, shape))
uncoords = coords[0]+5*(coords[1]+8*coords[2])
assert_equal(
np.ravel_multi_index(coords, shape, order='F'), uncoords)
assert_equal(coords, np.unravel_index(uncoords, shape, order='F'))
def compute(a, b):
"""
Compute an optimal displacement between two ndarrays.
Finds the displacement between two ndimensional arrays. Arrays must be
of the same size. Algorithm uses a cross correlation, computed efficiently
through an n-dimensional fft.
Parameters
----------
a : ndarray
The first array
b : ndarray
The second array
"""
from numpy.fft import rfftn, irfftn
from numpy import unravel_index, argmax
# compute real-valued cross-correlation in fourier domain
s = a.shape
f = rfftn(a)
f *= rfftn(b).conjugate()
c = abs(irfftn(f, s))
# find location of maximum
inds = unravel_index(argmax(c), s)
# fix displacements that are greater than half the total size
pairs = zip(inds, a.shape)
# cast to basic python int for serialization
adjusted = [int(d - n) if d > n // 2 else int(d) for (d, n) in pairs]
return Displacement(adjusted)
def update_tracker(response,img_size,pos,HOG_flag,scale_factor=1):
start_w,start_h = response.shape
w,h = img_size
px,py,ww,wh = pos
res_pos = np.unravel_index(response.argmax(),response.shape)
scale_w = 1.0*scale_factor*(ww*2)/start_w
scale_h = 1.0*scale_factor*(wh*2)/start_h
move = list(res_pos)
if not HOG_flag:
px_new = [px+1.0*move[0]*scale_w,px-(start_w-1.0*move[0])*scale_w][move[0]>start_w/2]
py_new = [py+1.0*move[1]*scale_h,py-(start_h-1.0*move[1])*scale_h][move[1]>start_h/2]
px_new = np.int(px_new)
py_new = np.int(py_new)
else:
move[0] = np.floor(res_pos[0]/32.0*(2*ww))
move[1] = np.floor(res_pos[1]/32.0*(2*wh))
px_new = [px+move[0],px-(2*ww-move[0])][move[0]>ww]
py_new = [py+move[1],py-(2*wh-move[1])][move[1]>wh]
if px_new<0: px_new = 0
if px_new>w: px_new = w-1
if py_new<0: py_new = 0
if py_new>h: py_new = h-1
ww_new = np.ceil(ww*scale_factor)
wh_new = np.ceil(wh*scale_factor)
new_pos = (px_new,py_new,ww_new,wh_new)
return new_pos
def act(self, observation, reward):
"""
Interact with and learn from the environment.
Returns the suggested control vector.
"""
observation = np.ravel_multi_index(observation, self.input_shape)
self.xp_q.update_reward(reward)
action = self.best_action(observation)
self.xp_q.add(observation, action)
action = np.unravel_index(action, self.output_shape)
return action
def stabilize(self, prior_columns, percent):
"""
This activates prior columns to force active in order to maintain
the given percent of column overlap between time steps. Always call
this between compute and learn!
"""
# num_active = (len(self.columns) + len(prior_columns)) / 2
num_active = len(self.columns)
overlap = self.columns.overlap(prior_columns)
stabile_columns = int(round(num_active * overlap))
target_columns = int(round(num_active * percent))
add_columns = target_columns - stabile_columns
if add_columns <= 0:
return
eligable_columns = np.setdiff1d(prior_columns.flat_index, self.columns.flat_index)
eligable_excite = self.raw_excitment[eligable_columns]
selected_col_nums = np.argpartition(-eligable_excite, add_columns-1)[:add_columns]
selected_columns = eligable_columns[selected_col_nums]
selected_index = np.unravel_index(selected_columns, self.columns.dimensions)
# Learn. Note: selected columns will learn twice. The previously
# active segments learn now, the current most excited segments in the
# method SP.learn().
# Or learn not at all if theres a bug in my code...
# if self.multisegment:
# if hasattr(self, 'prior_segment_excitement'):
# segment_excitement = self.prior_segment_excitement[selected_index]
# seg_idx = np.argmax(segment_excitement, axis=-1)
# self.proximal.learn_outputs(input_sdr=input_sdr,
# output_sdr=selected_index + (seg_idx,))
# self.prev_segment_excitement = self.segment_excitement
# else:
# 1/0
self.columns.flat_index = np.concatenate([self.columns.flat_index, selected_columns])
def _render(self, mode='human', close=False):
if close:
return
outfile = StringIO() if mode == 'ansi' else sys.stdout
for s in range(self.nS):
position = np.unravel_index(s, self.shape)
# print(self.s)
if self.s == s:
output = " x "
elif position == (3,11):
output = " T "
elif self._cliff[position]:
output = " C "
else:
output = " o "
if position[1] == 0:
output = output.lstrip()
if position[1] == self.shape[1] - 1:
output = output.rstrip()
output += "\n"
outfile.write(output)
outfile.write("\n")
def __init__(self):
self.shape = (7, 10)
nS = np.prod(self.shape)
nA = 4
# Wind strength
winds = np.zeros(self.shape)
winds[:,[3,4,5,8]] = 1
winds[:,[6,7]] = 2
# Calculate transition probabilities
P = {}
for s in range(nS):
position = np.unravel_index(s, self.shape)
P[s] = { a : [] for a in range(nA) }
P[s][UP] = self._calculate_transition_prob(position, [-1, 0], winds)
P[s][RIGHT] = self._calculate_transition_prob(position, [0, 1], winds)
P[s][DOWN] = self._calculate_transition_prob(position, [1, 0], winds)
P[s][LEFT] = self._calculate_transition_prob(position, [0, -1], winds)
# We always start in state (3, 0)
isd = np.zeros(nS)
isd[np.ravel_multi_index((3,0), self.shape)] = 1.0
super(WindyGridworldEnv, self).__init__(nS, nA, P, isd)
cleaners.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def argmax(a):
""" Return unravelled index of the maximum
param: a: array to be searched
"""
return numpy.unravel_index(a.argmax(), a.shape)
cleaners.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def find_max_abs_stack(stack, windowstack, couplingmatrix):
"""Find the location and value of the absolute maximum in this stack
:param stack: stack to be searched
:param windowstack: Window for the search
:param couplingmatrix: Coupling matrix between difference scales
:return: x, y, scale
"""
pabsmax = 0.0
pscale = 0
px = 0
py = 0
nscales = stack.shape[0]
assert nscales > 0
pshape = [stack.shape[1], stack.shape[2]]
for iscale in range(nscales):
if windowstack is not None:
resid = stack[iscale, :, :] * windowstack[iscale, :, :] / couplingmatrix[iscale, iscale]
else:
resid = stack[iscale, :, :] / couplingmatrix[iscale, iscale]
# Find the peak in the scaled residual image
mx, my = numpy.unravel_index(numpy.abs(resid).argmax(), pshape)
# Is this the peak over all scales?
thisabsmax = numpy.abs(resid[mx, my])
if thisabsmax > pabsmax:
px = mx
py = my
pscale = iscale
pabsmax = thisabsmax
return px, py, pscale
def fit_gaussian(x, y, z_2d, save_fits=False):
z = z_2d
max_idx = np.unravel_index(z.argmax(), z.shape)
max_row = max_idx[0] - 1
max_col = max_idx[1] - 1
z_max_row = z[max_row, :]
z_max_col = z[:, max_col]
A = z[max_row, max_col]
p_guess_x = (A, x[max_col], 0.1*(x[-1] - x[0]))
p_guess_y = (A, y[max_row], 0.1*(y[-1] - y[0]))
coeffs_x, var_matrix_x = sciopt.curve_fit(gaussian, x, z_max_row, p_guess_x)
coeffs_y, var_matrix_y = sciopt.curve_fit(gaussian, y, z_max_col, p_guess_y)
c_x = (x[-1]-x[0])*(max_col+1)/x.size + x[0]
c_y = (y[-1]-y[0])*(y.size-(max_row+1))/y.size + y[0]
centre = (c_x, c_y)
sigma = np.array([coeffs_x[2], coeffs_y[2]])
fwhm = 2.355 * sigma
sigma_2 = 1.699 * fwhm
if save_fits:
with open('x_fit.dat', 'w') as fs:
for c in np.c_[x, z_max_row, gaussian(x, *coeffs_x)]:
s = ','.join([str(v) for v in c])
fs.write(s+'\n')
with open('y_fit.dat', 'w') as fs:
for c in np.c_[y, z_max_col, gaussian(y, *coeffs_y)]:
s = ','.join([str(v) for v in c])
fs.write(s+'\n')
return A, centre, sigma_2
def argmax(x):
return np.unravel_index(x.argmax(), x.shape)
def get_test_tensor(self, test_data, shape, start, end):
slice_idx = self._slice_test_data(test_data, start, end)
num_users = end - start
num_items = shape[1]
num_fdbks = shape[2]
slice_shp = (num_users, num_items, num_fdbks)
idx_flat = np.ravel_multi_index(slice_idx, slice_shp)
shp_flat = (num_users*num_items, num_fdbks)
idx = np.unravel_index(idx_flat, shp_flat)
val = np.ones_like(slice_idx[2])
test_tensor_unfolded = csr_matrix((val, idx), shape=shp_flat, dtype=val.dtype)
return test_tensor_unfolded, slice_idx