Python numpy.unravel_index() Examples

The following are 30 code examples for showing how to use numpy.unravel_index(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: pyscf   Author: pyscf   File: addons.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 2
Project: pyscf   Author: pyscf   File: mf.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: Dispersion-based-Clustering   Author: gddingcs   File: bottom_up.py    License: MIT License 6 votes vote down vote up
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 
Example 4
Project: Dispersion-based-Clustering   Author: gddingcs   File: bottom_up.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: Dispersion-based-Clustering   Author: gddingcs   File: bottom_up.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: ffn   Author: google   File: bounding_box.py    License: Apache License 2.0 6 votes vote down vote up
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') 
Example 7
Project: ffn   Author: google   File: bounding_box.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 8
Project: rl_algorithms   Author: DanielTakeshi   File: cliff_walking.py    License: MIT License 6 votes vote down vote up
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) 
Example 9
Project: rl_algorithms   Author: DanielTakeshi   File: windy_gridworld.py    License: MIT License 6 votes vote down vote up
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") 
Example 10
Project: TNT   Author: GaoangW   File: track_lib.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 11
Project: TNT   Author: GaoangW   File: tracklet_utils_3d.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: TNT   Author: GaoangW   File: track_lib.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 13
Project: lambda-packs   Author: ryfeus   File: lil.py    License: MIT License 6 votes vote down vote up
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 
Example 14
Project: RelativePose   Author: zhenpeiyang   File: rputil.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 15
Project: DRL_DeliveryDuel   Author: ArztSamuel   File: cliffwalking.py    License: MIT License 6 votes vote down vote up
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') 
Example 16
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example 17
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_utils.py    License: Apache License 2.0 5 votes vote down vote up
def find_max_violation(a, b, rtol=None, atol=None):
    """Finds and returns the location of maximum violation."""
    rtol = get_rtol(rtol)
    atol = get_atol(atol)
    diff = np.abs(a-b)
    tol = atol + rtol*np.abs(b)
    violation = diff/(tol+1e-20)
    loc = np.argmax(violation)
    idx = np.unravel_index(loc, violation.shape)
    return idx, np.max(violation) 
Example 18
Project: QCElemental   Author: MolSSI   File: scipy_hungarian.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _step4(state):
    """
    Find a noncovered zero and prime it. If there is no starred zero
    in the row containing this primed zero, Go to Step 5. Otherwise,
    cover this row and uncover the column containing the starred
    zero. Continue in this manner until there are no uncovered zeros
    left. Save the smallest uncovered value and Go to Step 6.
    """
    # We convert to int as numpy operations are faster on int
    C = (state.C == 0).astype(int)
    covered_C = C * state.row_uncovered[:, np.newaxis]
    covered_C *= np.asarray(state.col_uncovered, dtype=int)
    n = state.C.shape[0]
    m = state.C.shape[1]

    while True:
        # Find an uncovered zero
        row, col = np.unravel_index(np.argmax(covered_C), (n, m))
        if covered_C[row, col] == 0:
            return _step6
        else:
            state.marked[row, col] = 2
            # Find the first starred element in the row
            star_col = np.argmax(state.marked[row] == 1)
            if state.marked[row, star_col] != 1:
                # Could not find one
                state.Z0_r = row
                state.Z0_c = col
                return _step5
            else:
                col = star_col
                state.row_uncovered[row] = False
                state.col_uncovered[col] = True
                covered_C[:, col] = C[:, col] * (np.asarray(state.row_uncovered, dtype=int))
                covered_C[row] = 0 
Example 19
Project: TVQAplus   Author: jayleicn   File: model_utils.py    License: MIT License 5 votes vote down vote up
def topN_array_2d(array_2d, topN=None):
    """ Get topN indices and values of a 2d array, return a tuple of indices and their values,
    ranked by the value
    """
    row_indices, column_indices = np.unravel_index(np.argsort(array_2d, axis=None), array_2d.shape)
    row_indices = row_indices[::-1][:topN]
    column_indices = column_indices[::-1][:topN]
    sorted_values = array_2d[row_indices, column_indices]
    sorted_triples = zip(row_indices, column_indices, sorted_values)
    return sorted_triples 
Example 20
Project: scarlet   Author: pmelchior   File: measure.py    License: MIT License 5 votes vote down vote up
def max_pixel(component):
    """Determine pixel with maximum value

    Parameters
    ----------
    component: `scarlet.Component` or `scarlet.ComponentTree`
        Component to analyze
    """
    model = component.get_model()
    return tuple(
        np.unravel_index(np.argmax(model), model.shape) + component.bbox.origin
    ) 
Example 21
Project: pyscf   Author: pyscf   File: mf.py    License: Apache License 2.0 5 votes vote down vote up
def polariz_nonin_ave_matelem(self, comega):
    from scipy.sparse import spmatrix 
    """ Computes the non-interacting optical polarizability via the dipole matrix elements."""

    x,y,z = map(spmatrix.toarray, self.dipole_coo())
    i2d = array((x,y,z))
    n = self.mo_occ.shape[-1]
    eemax = max(comega.real)+20.0*max(comega.imag)
    
    p = zeros((len(comega)), dtype=np.complex128) # result to accumulate

    #print(__name__, 'Fermi energy', self.fermi_energy)
    #np.set_printoptions(linewidth=1000)
    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]
      #print(o[:10])
      #print(e[:10])

      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 
Example 22
Project: razzy-spinner   Author: rafasashi   File: gaac.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cluster_vectorspace(self, vectors, trace=False):
        # variables describing the initial situation
        N = len(vectors)
        cluster_len = [1]*N
        cluster_count = N
        index_map = numpy.arange(N)

        # construct the similarity matrix
        dims = (N, N)
        dist = numpy.ones(dims, dtype=numpy.float)*numpy.inf
        for i in range(N):
            for j in range(i+1, N):
                dist[i, j] = cosine_distance(vectors[i], vectors[j])

        while cluster_count > max(self._num_clusters, 1):
            i, j = numpy.unravel_index(dist.argmin(), dims)
            if trace:
                print("merging %d and %d" % (i, j))

            # update similarities for merging i and j
            self._merge_similarities(dist, cluster_len, i, j)

            # remove j
            dist[:, j] = numpy.inf
            dist[j, :] = numpy.inf

            # merge the clusters
            cluster_len[i] = cluster_len[i]+cluster_len[j]
            self._dendrogram.merge(index_map[i], index_map[j])
            cluster_count -= 1

            # update the index map to reflect the indexes if we
            # had removed j
            index_map[j+1:] -= 1
            index_map[j] = N

        self.update_clusters(self._num_clusters) 
Example 23
Project: ncvx   Author: cvxgrp   File: tour.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _project(self, matrix):
        if self.is_scalar():
            return 1
        else:
            matrix = matrix.copy()
            # Greedy algorithm.
            # Fix largest entry that still could be a tour.
            # Recurse.
            tour = np.zeros(self.shape[0], dtype=int) - 1
            result = np.zeros(self.shape)
            for i in range(self.shape[0]):
                while True:
                    idx = np.argmax(matrix)
                    row, col = list(zip(*np.unravel_index([idx], self.shape)))[0]
                    # Check that consistent with tour.
                    tour[row] = col
                    if self._no_cycles(tour):
                        result[row, col] = 1
                        matrix[row,:] = -np.inf
                        matrix[:,col] = -np.inf
                        break
                    else:
                        matrix[row, col] = -np.inf
                        tour[row] = -1
                    assert not (matrix == -np.inf).all()
            return result 
Example 24
Project: ncvx   Author: cvxgrp   File: choose.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _project(self, matrix):
        lin_index = np.squeeze(np.asarray(matrix)).flatten().argsort()[::-1]
        sub_index = np.unravel_index(lin_index[:self.k], matrix.shape)
        matrix[:] = 0.0
        matrix[sub_index] = 1.0
        return matrix

    # In the relaxation, we have 0 <= var <= 1. 
Example 25
Project: Dispersion-based-Clustering   Author: gddingcs   File: bottom_up.py    License: MIT License 5 votes vote down vote up
def select_merge_data_v2(self, u_feas, labels, linkages):
        linkages += np.tril(100000 * np.ones_like(linkages))
        ind = np.unravel_index(np.argsort(linkages, axis=None),
                               linkages.shape)  
        idx1 = ind[0] 
        idx2 = ind[1] 
        return idx1, idx2 
Example 26
Project: insightface   Author: deepinsight   File: test.py    License: MIT License 5 votes vote down vote up
def get(self, img):
    ret = self.detector.detect_face(img, det_type = 0)
    if ret is None:
      return None
    bbox, points = ret
    if bbox.shape[0]==0:
      return None
    bbox = bbox[0,0:4]
    points = points[0,:].reshape((2,5)).T
    M = img_helper.estimate_trans_bbox(bbox, self.image_size[0], s = 2.0)
    rimg = cv2.warpAffine(img, M, self.image_size, borderValue = 0.0)
    img = cv2.cvtColor(rimg, cv2.COLOR_BGR2RGB)
    img = np.transpose(img, (2,0,1)) #3*112*112, RGB
    input_blob = np.zeros( (1, 3, self.image_size[1], self.image_size[0]),dtype=np.uint8 )
    input_blob[0] = img
    ta = datetime.datetime.now()
    data = mx.nd.array(input_blob)
    db = mx.io.DataBatch(data=(data,))
    self.model.forward(db, is_train=False)
    alabel = self.model.get_outputs()[-1].asnumpy()[0]
    tb = datetime.datetime.now()
    print('module time cost', (tb-ta).total_seconds())
    ret = np.zeros( (alabel.shape[0], 2), dtype=np.float32)
    for i in range(alabel.shape[0]):
      a = cv2.resize(alabel[i], (self.image_size[1], self.image_size[0]))
      ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
      #ret[i] = (ind[0], ind[1]) #h, w
      ret[i] = (ind[1], ind[0]) #w, h
    return ret, M 
Example 27
Project: MnemonicReader   Author: HKUST-KnowComp   File: model.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decode(score_s, score_e, top_n=1, max_len=None):
        """Take argmax of constrained score_s * score_e.

        Args:
            score_s: independent start predictions
            score_e: independent end predictions
            top_n: number of top scored pairs to take
            max_len: max span length to consider
        """
        pred_s = []
        pred_e = []
        pred_score = []
        max_len = max_len or score_s.size(1)
        for i in range(score_s.size(0)):
            # Outer product of scores to get full p_s * p_e matrix
            scores = torch.ger(score_s[i], score_e[i])

            # Zero out negative length and over-length span scores
            scores.triu_().tril_(max_len - 1)

            # Take argmax or top n
            scores = scores.numpy()
            scores_flat = scores.flatten()
            if top_n == 1:
                idx_sort = [np.argmax(scores_flat)]
            elif len(scores_flat) < top_n:
                idx_sort = np.argsort(-scores_flat)
            else:
                idx = np.argpartition(-scores_flat, top_n)[0:top_n]
                idx_sort = idx[np.argsort(-scores_flat[idx])]
            s_idx, e_idx = np.unravel_index(idx_sort, scores.shape)
            pred_s.append(s_idx)
            pred_e.append(e_idx)
            pred_score.append(scores_flat[idx_sort])
        del score_s, score_e
        return pred_s, pred_e, pred_score 
Example 28
Project: recruit   Author: Frank-qlu   File: test_index_tricks.py    License: Apache License 2.0 5 votes vote down vote up
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')) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_index_tricks.py    License: Apache License 2.0 5 votes vote down vote up
def test_writeability(self):
        # See gh-7269
        x, y = np.unravel_index([1, 2, 3], (4, 5))
        assert_(x.flags.writeable)
        assert_(y.flags.writeable) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_index_tricks.py    License: Apache License 2.0 5 votes vote down vote up
def test_0d(self):
        # gh-580
        x = np.unravel_index(0, ())
        assert_equal(x, ())

        assert_raises_regex(ValueError, "0d array", np.unravel_index, [0], ())
        assert_raises_regex(
            ValueError, "out of bounds", np.unravel_index, [1], ())