本文整理汇总了Python中numpy.unravel_index方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.unravel_index方法的具体用法?Python numpy.unravel_index怎么用?Python numpy.unravel_index使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.unravel_index方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: large_ci
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def large_ci(ci, norb, nelec, tol=LARGE_CI_TOL, return_strs=RETURN_STRS):
'''Search for the largest CI coefficients
'''
neleca, nelecb = _unpack_nelec(nelec)
na = cistring.num_strings(norb, neleca)
nb = cistring.num_strings(norb, nelecb)
assert(ci.shape == (na, nb))
addra, addrb = numpy.where(abs(ci) > tol)
if addra.size == 0:
# No large CI coefficient > tol, search for the largest coefficient
addra, addrb = numpy.unravel_index(numpy.argmax(abs(ci)), ci.shape)
addra = numpy.asarray([addra])
addrb = numpy.asarray([addrb])
strsa = cistring.addrs2str(norb, neleca, addra)
strsb = cistring.addrs2str(norb, nelecb, addrb)
if return_strs:
strsa = [bin(x) for x in strsa]
strsb = [bin(x) for x in strsb]
return list(zip(ci[addra,addrb], strsa, strsb))
else:
occslsta = cistring._strs2occslst(strsa, norb)
occslstb = cistring._strs2occslst(strsb, norb)
return list(zip(ci[addra,addrb], occslsta, occslstb))
示例2: nonin_osc_strength
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def nonin_osc_strength(self):
from scipy.sparse import spmatrix
""" Computes the non-interacting oscillator strengths and energies """
x,y,z = map(spmatrix.toarray, self.dipole_coo())
i2d = array((x,y,z))
n = self.mo_occ.shape[-1]
p = zeros((len(comega)), dtype=np.complex128) # result to accumulate
for s in range(self.nspin):
o,e,cc = self.mo_occ[0,s],self.mo_energy[0,s],self.mo_coeff[0,s,:,:,0]
oo1,ee1 = np.subtract.outer(o,o).reshape(n*n), np.subtract.outer(e,e).reshape(n*n)
idx = unravel_index( np.intersect1d(where(oo1<0.0), where(ee1<eemax)), (n,n))
ivrt,iocc = array(list(set(idx[0]))), array(list(set(idx[1])))
voi2d = einsum('nia,ma->nmi', einsum('iab,nb->nia', i2d, cc[ivrt]), cc[iocc])
t2osc = 2.0/3.0*einsum('voi,voi->vo', voi2d, voi2d)
t2w = np.subtract.outer(e[ivrt],e[iocc])
t2o = -np.subtract.outer(o[ivrt],o[iocc])
for iw,w in enumerate(comega):
p[iw] += 0.5*(t2osc*((t2o/(w-t2w))-(t2o/(w+t2w)))).sum()
return p
示例3: select_merge_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def select_merge_data(self, u_feas, label, label_to_images, ratio_n, dists):
dists.add_(torch.tril(100000 * torch.ones(len(u_feas), len(u_feas))))#blocking the triangle
cnt = torch.FloatTensor([len(label_to_images[label[idx]]) for idx in range(len(u_feas))])
dists += ratio_n * (cnt.view(1, len(cnt)) + cnt.view(len(cnt), 1)) # dist += |A|+|B|
for idx in range(len(u_feas)):
for j in range(idx + 1, len(u_feas)):
if label[idx] == label[j]:
dists[idx, j] = 100000 # set the distance within the same cluster
dists = dists.numpy()
ind = np.unravel_index(np.argsort(dists, axis=None), dists.shape) # with axis=None all numbers are sorted and unravel_index transforms the sorted index into ind for each dimension
idx1 = ind[0] # the first dimension index
idx2 = ind[1] # the second dimension index
return idx1, idx2
示例4: select_merge_data_v2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def select_merge_data_v2(self, u_feas, labels, linkages):
linkages+=(np.tril(100000 * np.ones((len(u_feas), len(u_feas))))) # blocking the triangle
print('Linkage adding')
for idx in range(len(u_feas)):
for j in range(idx + 1, len(u_feas)):
if labels[idx] == labels[j]:
linkages[idx, j] = 100000 # set the distance within the same cluster
ind = np.unravel_index(np.argsort(linkages, axis=None),
linkages.shape) # with axis=None all numbers are sorted and unravel_index transforms the sorted index into ind for each dimension
idx1 = ind[0] # the first cluster index
idx2 = ind[1] # the second cluster index
print('Linkage add finished')
return idx1, idx2
#after
示例5: select_merge_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def select_merge_data(self, u_feas, label, label_to_images, ratio_n, dists):
dists.add_(torch.tril(100000 * torch.ones(len(u_feas), len(u_feas))))
cnt = torch.FloatTensor([len(label_to_images[label[idx]]) for idx in range(len(u_feas))])
dists += ratio_n * (cnt.view(1, len(cnt)) + cnt.view(len(cnt), 1))
for idx in range(len(u_feas)):
for j in range(idx + 1, len(u_feas)):
if label[idx] == label[j]:
dists[idx, j] = 100000
dists = dists.numpy()
ind = np.unravel_index(np.argsort(dists, axis=None), dists.shape)
idx1 = ind[0]
idx2 = ind[1]
return idx1, idx2
示例6: offset_to_index
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def offset_to_index(self, index, offset):
"""Calculate the index of another box at offset w.r.t.
current index.
Args:
index: the current flat index from which to calculate the offset index.
offset: the xyz offset from current index at which to calculate the new
index.
Returns:
The flat index at offset from current index, or None if the given offset
goes beyond the range of sub-boxes.
This is usually used to calculate the boxes that neighbor the current box.
"""
coords = np.unravel_index(index, self.total_sub_boxes_xyz, order='F')
offset_coords = np.array(coords) + offset
if np.any(offset_coords < 0) or np.any(
offset_coords >= self.total_sub_boxes_xyz):
return None
return np.ravel_multi_index(
offset_coords, self.total_sub_boxes_xyz, order='F')
示例7: tag_border_locations
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def tag_border_locations(self, index):
"""Checks whether a box touches the border of the BoundingBox.
Args:
index: flat index identifying the box to check
Returns:
2-tuple of bool 3d ndarrays (dim order: x, y, z).
True if the box touches the border at the start/end (respectively for the
1st and 2nd element of the tuple) of the bbox along the given dimension.
"""
coords_xyz = np.array(
np.unravel_index(index, self.total_sub_boxes_xyz, order='F'))
is_start = coords_xyz == 0
is_end = coords_xyz == self.total_sub_boxes_xyz - 1
return is_start, is_end
示例8: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def __init__(self):
self.shape = (4, 12)
nS = np.prod(self.shape)
nA = 4
# Cliff Location
self._cliff = np.zeros(self.shape, dtype=np.bool)
self._cliff[3, 1:-1] = True
# 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])
P[s][RIGHT] = self._calculate_transition_prob(position, [0, 1])
P[s][DOWN] = self._calculate_transition_prob(position, [1, 0])
P[s][LEFT] = self._calculate_transition_prob(position, [0, -1])
# We always start in state (3, 0)
isd = np.zeros(nS)
isd[np.ravel_multi_index((3,0), self.shape)] = 1.0
super(CliffWalkingEnv, self).__init__(nS, nA, P, isd)
示例9: _render
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
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,7):
output = " T "
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")
示例10: bbox_associate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def bbox_associate(overlap_mat, IOU_thresh):
idx1 = []
idx2 = []
new_overlap_mat = overlap_mat.copy()
while 1:
idx = np.unravel_index(np.argmax(new_overlap_mat, axis=None), new_overlap_mat.shape)
if new_overlap_mat[idx]<IOU_thresh:
break
else:
idx1.append(idx[0])
idx2.append(idx[1])
new_overlap_mat[idx[0],:] = 0
new_overlap_mat[:,idx[1]] = 0
idx1 = np.array(idx1)
idx2 = np.array(idx2)
return idx1, idx2
示例11: bbox_associate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def bbox_associate(overlap_mat, IOU_thresh):
idx1 = []
idx2 = []
while 1:
idx = np.unravel_index(np.argmax(overlap_mat, axis=None), overlap_mat.shape)
if overlap_mat[idx]<IOU_thresh:
break
else:
idx1.append(idx[0])
idx2.append(idx[1])
overlap_mat[idx[0],:] = 0
overlap_mat[:,idx[1]] = 0
idx1 = np.array(idx1)
idx2 = np.array(idx2)
return idx1, idx2
示例12: reshape
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def reshape(self, shape, order='C'):
if type(order) != str or order != 'C':
raise ValueError(("Sparse matrices do not support "
"an 'order' parameter."))
if type(shape) != tuple:
raise TypeError("a tuple must be passed in for 'shape'")
if len(shape) != 2:
raise ValueError("a length-2 tuple must be passed in for 'shape'")
new = lil_matrix(shape, dtype=self.dtype)
j_max = self.shape[1]
# Size is ambiguous for sparse matrices, so in order to check 'total
# dimension', we need to take the product of their dimensions instead
if new.shape[0] * new.shape[1] != self.shape[0] * self.shape[1]:
raise ValueError("the product of the dimensions for the new sparse "
"matrix must equal that of the original matrix")
for i, row in enumerate(self.rows):
for col, j in enumerate(row):
new_r, new_c = np.unravel_index(i*j_max + j, shape)
new[new_r, new_c] = self[i, j]
return new
示例13: Sampling
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def Sampling(heatmap, K):
# heatmap: [n,h,w]
# return: [n,K,2]
heatmap = np.exp(-heatmap/2)
n,h,w=heatmap.shape
pt = np.zeros([n,K,2])
WINDOW_SZ = 15
for i in range(n):
for j in range(K):
idx=np.argmax(heatmap[i])
coord=np.unravel_index(idx,heatmap[i].shape)[::-1]
pt[i,j,:]=coord
# suppress the neighbors
topl=[max(0,coord[0] - WINDOW_SZ),max(0,coord[1] - WINDOW_SZ)]
botr=[min(w-1,coord[0] + WINDOW_SZ),min(h-1,coord[1] + WINDOW_SZ)]
heatmap[i][topl[1]:botr[1],topl[0]:botr[0]] = heatmap[i].min()
return pt
示例14: render
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def render(self, mode='human'):
outfile = sys.stdout
for s in range(self.nS):
position = np.unravel_index(s, self.shape)
if self.s == s:
output = " x "
# Print terminal state
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')
示例15: curve_intersection
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import unravel_index [as 别名]
def curve_intersection(c1, c2, grid=16):
'''
curve_intersect(c1, c2) yields the parametric distances (t1, t2) such that c1(t1) == c2(t2).
The optional parameter grid may specify the number of grid-points
to use in the initial search for a start-point (default: 16).
'''
from scipy.optimize import minimize
from neuropythy.geometry import segment_intersection_2D
if c1.coordinates.shape[1] > c2.coordinates.shape[1]:
(t1,t2) = curve_intersection(c2, c1, grid=grid)
return (t2,t1)
# before doing a search, see if there are literal exact intersections of the segments
x1s = c1.coordinates.T
x2s = c2.coordinates
for (ts,te,xs,xe) in zip(c1.t[:-1], c1.t[1:], x1s[:-1], x1s[1:]):
pts = segment_intersection_2D((xs,xe), (x2s[:,:-1], x2s[:,1:]))
ii = np.where(np.isfinite(pts[0]))[0]
if len(ii) > 0:
ii = ii[0]
def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
t01 = 0.5*(ts + te)
t02 = 0.5*(c2.t[ii] + c2.t[ii+1])
(t1,t2) = minimize(f, (t01, t02)).x
return (t1,t2)
if pimms.is_vector(grid): (ts1,ts2) = [c.t[0] + (c.t[-1] - c.t[0])*grid for c in (c1,c2)]
else: (ts1,ts2) = [np.linspace(c.t[0], c.t[-1], grid) for c in (c1,c2)]
(pts1,pts2) = [c(ts) for (c,ts) in zip([c1,c2],[ts1,ts2])]
ds = np.sqrt([np.sum((pts2.T - pp)**2, axis=1) for pp in pts1.T])
(ii,jj) = np.unravel_index(np.argmin(ds), ds.shape)
(t01,t02) = (ts1[ii], ts2[jj])
ttt = []
def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
(t1,t2) = minimize(f, (t01, t02)).x
return (t1,t2)