Python numpy 模块,require() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.require()

项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(image,the_net):
    inputs = []
    try:
        tmp_input = image
        tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
        tmp_input = tmp_input[11:11+128,11:11+128];
        tmp_input = np.subtract(tmp_input,mean)
        tmp_input = tmp_input.transpose((2, 0, 1))
        tmp_input = np.require(tmp_input, dtype=np.float32)
    except Exception as e:
        raise Exception("Image damaged or illegal file format")
        return
    the_net.blobs['data'].reshape(1, *tmp_input.shape)
    the_net.reshape()
    the_net.blobs['data'].data[...] = tmp_input
    the_net.forward()
    scores = the_net.blobs['prob'].data[0]
    return copy.deepcopy(scores)
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(the_net,image):
  inputs = []
  if not os.path.exists(image):
    raise Exception("Image path not exist")
    return
  try:
    tmp_input = cv2.imread(image)
    tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
    tmp_input = tmp_input[11:11+128,11:11+128]
    tmp_input = np.subtract(tmp_input,mean)
    tmp_input = tmp_input.transpose((2, 0, 1))
    tmp_input = np.require(tmp_input, dtype=np.float32)
  except Exception as e:
    #raise Exception("Image damaged or illegal file format")
    return None
  the_net.blobs['data'].reshape(1, *tmp_input.shape)
  the_net.reshape()
  the_net.blobs['data'].data[...] = tmp_input
  the_net.forward()
  scores = copy.deepcopy(the_net.blobs['feature'].data)
  return scores
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(image,the_net):
    inputs = []
    try:
        tmp_input = image
        tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
        tmp_input = tmp_input[13:13+224,13:13+224];
        tmp_input = np.subtract(tmp_input,mean)
        tmp_input = tmp_input.transpose((2, 0, 1))
        tmp_input = np.require(tmp_input, dtype=np.float32)
    except Exception as e:
        raise Exception("Image damaged or illegal file format")
        return
    the_net.blobs['data'].reshape(1, *tmp_input.shape)
    the_net.reshape()
    the_net.blobs['data'].data[...] = tmp_input
    the_net.forward()
    scores = the_net.blobs['prob'].data[0]
    return copy.deepcopy(scores)
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(image,the_net):
    inputs = []
    try:
        tmp_input = image
        tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
        tmp_input = tmp_input[11:11+128,11:11+128];
        tmp_input = np.subtract(tmp_input,mean)
        tmp_input = tmp_input.transpose((2, 0, 1))
        tmp_input = np.require(tmp_input, dtype=np.float32)
    except Exception as e:
        raise Exception("Image damaged or illegal file format")
        return
    the_net.blobs['data'].reshape(1, *tmp_input.shape)
    the_net.reshape()
    the_net.blobs['data'].data[...] = tmp_input
    the_net.forward()
    scores = the_net.blobs['prob'].data[0]
    return copy.deepcopy(scores)
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(the_net,image):
  inputs = []
  if not os.path.exists(image):
    raise Exception("Image path not exist")
    return
  try:
    tmp_input = cv2.imread(image)
    tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
    tmp_input = tmp_input[13:13+224,13:13+224]
    #tmp_input = np.subtract(tmp_input,mean)
    tmp_input = tmp_input.transpose((2, 0, 1))
    tmp_input = np.require(tmp_input, dtype=np.float32)
  except Exception as e:
    #raise Exception("Image damaged or illegal file format")
    return None
  the_net.blobs['data'].reshape(1, *tmp_input.shape)
  the_net.reshape()
  the_net.blobs['data'].data[...] = tmp_input
  the_net.forward()
  scores = copy.deepcopy(the_net.blobs['fc6'].data)
  return scores
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(image,the_net):
    inputs = []
    try:
        tmp_input = image
        tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
        tmp_input = tmp_input[13:13+224,13:13+224];
        tmp_input = np.subtract(tmp_input,mean)
        tmp_input = tmp_input.transpose((2, 0, 1))
        tmp_input = np.require(tmp_input, dtype=np.float32)
    except Exception as e:
        raise Exception("Image damaged or illegal file format")
        return
    the_net.blobs['data'].reshape(1, *tmp_input.shape)
    the_net.reshape()
    the_net.blobs['data'].data[...] = tmp_input
    the_net.forward()
    scores = the_net.blobs['prob'].data[0]
    return copy.deepcopy(scores)
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(image,the_net):
    inputs = []
    try:
        tmp_input = image
        tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
        tmp_input = tmp_input[13:13+224,13:13+224];
        tmp_input = np.subtract(tmp_input,mean)
        tmp_input = tmp_input.transpose((2, 0, 1))
        tmp_input = np.require(tmp_input, dtype=np.float32)
    except Exception as e:
        raise Exception("Image damaged or illegal file format")
        return
    the_net.blobs['data'].reshape(1, *tmp_input.shape)
    the_net.reshape()
    the_net.blobs['data'].data[...] = tmp_input
    the_net.forward()
    scores = the_net.blobs['prob'].data[0]
    return copy.deepcopy(scores)
项目:EmotiW-2017-Audio-video-Emotion-Recognition    作者:xujinchang    | 项目源码 | 文件源码
def predict(the_net,image):
  inputs = []
  if not os.path.exists(image):
    raise Exception("Image path not exist")
    return
  try:
    tmp_input = cv2.imread(image)
    tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
    tmp_input = tmp_input[13:13+224,13:13+224]
    tmp_input = np.subtract(tmp_input,mean)
    tmp_input = tmp_input.transpose((2, 0, 1))
    tmp_input = np.require(tmp_input, dtype=np.float32)
  except Exception as e:
    #raise Exception("Image damaged or illegal file format")
    return None
  the_net.blobs['data'].reshape(1, *tmp_input.shape)
  the_net.reshape()
  the_net.blobs['data'].data[...] = tmp_input
  the_net.forward()
  scores = copy.deepcopy(the_net.blobs['fc6'].data)
  return scores
项目:TPN    作者:myfavouritekk    | 项目源码 | 文件源码
def _propagate_boxes(boxes, annot_proto, frame_id):
    pred_boxes = []
    annots = []
    for annot in annot_proto['annotations']:
        for idx, box in enumerate(annot['track']):
            if box['frame'] == frame_id and len(annot['track']) > idx + 1:
                gt1 = box['bbox']
                gt2 = annot['track'][idx+1]['bbox']
                delta = bbox_transform(np.asarray([gt1]), np.asarray([gt2]))
                annots.append((gt1, delta))
    gt1 = [annot[0] for annot in annots]
    overlaps = bbox_overlaps(np.require(boxes, dtype=np.float),
                             np.require(gt1, dtype=np.float))
    assert len(overlaps) == len(boxes)
    for gt_overlaps, box in zip(overlaps, boxes):
        max_overlap = np.max(gt_overlaps)
        max_gt = np.argmax(gt_overlaps)
        if max_overlap < 0.5:
            pred_boxes.append(box)
        else:
            delta = annots[max_gt][1]
            pred_boxes.append(bbox_transform_inv(np.asarray([box]), delta)[0].tolist())
    return pred_boxes
项目:heliopy    作者:heliopython    | 项目源码 | 文件源码
def epoch_to_epoch16(self, epoch):
        """
        Converts a CDF EPOCH to a CDF EPOCH16 value

        Parameters
        ==========
        epoch : double
            EPOCH to convert. Lists and numpy arrays are acceptable.

        Returns
        =======
        out : (double, double)
            EPOCH16 corresponding to epoch
        """
        e = numpy.require(epoch, numpy.float64)
        s = numpy.trunc(e / 1000.0)
        #ugly numpy stuff, probably a better way....
        res = numpy.hstack((s, (e - s * 1000.0) * 1e9))
        if len(res) <= 2:
            return res
        newshape = list(res.shape[0:-2])
        newshape.append(res.shape[-1] // 2)
        newshape.append(2)
        return numpy.rollaxis(res.reshape(newshape), -1, -2)
项目:heliopy    作者:heliopython    | 项目源码 | 文件源码
def epoch16_to_epoch(self, epoch16):
        """
        Converts a CDF EPOCH16 to a CDF EPOCH value

        Parameters
        ==========
        epoch16 : (double, double)
            EPOCH16 to convert. Lists and numpy arrays are acceptable.
            LAST dimension should be 2: the two pairs of EPOCH16

        Returns
        =======
        out : double
            EPOCH corresponding to epoch16
        """
        e = numpy.require(epoch16, numpy.float64)
        return e[..., 0] * 1000.0 + numpy.round(e[..., 1] / 1e9)
项目:heliopy    作者:heliopython    | 项目源码 | 文件源码
def create_array(self):
        """Creates a numpy array to hold the data from this slice

        Returns
        =======
        out : numpy.array
            array sized, typed, and dimensioned to hold data from
            this slice
        """
        counts = self.counts
        degen = self.degen
        if self.column:
            counts = self.reorder(counts)
            degen = self.reorder(degen)
        #TODO: Forcing C order for now, revert to using self.column later
        array = numpy.empty(
            [counts[i] for i in range(len(counts)) if not degen[i]],
            self.zvar._np_type(), order='C')
        return numpy.require(array, requirements=('C', 'A', 'W'))
项目:mimclib    作者:StochasticNumerics    | 项目源码 | 文件源码
def unique_rows(A, return_index=False, return_inverse=False):
    """
    Similar to MATLAB's unique(A, 'rows'), this returns B, I, J
    where B is the unique rows of A and I and J satisfy
    A = B[J,:] and B = A[I,:]

    Returns I if return_index is True
    Returns J if return_inverse is True
    """
    A = np.require(A, requirements='C')
    assert A.ndim == 2, "array must be 2-dim'l"
    B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
                  return_index=return_index,
                  return_inverse=return_inverse)

    if return_index or return_inverse:
        return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
            + B[1:]
    else:
        return B.view(A.dtype).reshape((-1, A.shape[1]), order='C')
项目:indigo    作者:mbdriscoll    | 项目源码 | 文件源码
def test_fft(backend, batch, x, y, z):
    b = backend()
    N = (z, y, x, batch)
    v = np.random.rand(*N) + 1j*np.random.rand(*N)
    v = np.require(v, dtype=np.dtype('complex64'), requirements='F')
    ax = (0,1,2)

    # check forward
    w_exp = np.fft.fftn(v, axes=ax)
    v_d = b.copy_array(v)
    u_d = b.copy_array(v)
    b.fftn(u_d, v_d)
    w_act = u_d.to_host()
    np.testing.assert_allclose(w_act, w_exp, atol=1e-2)

    # check adjoint
    v_exp = np.fft.ifftn(w_act, axes=ax) * (x*y*z)
    v_d = b.copy_array(w_act)
    u_d = b.copy_array(w_act)
    b.ifftn(u_d, v_d)
    v_act = u_d.to_host()
    np.testing.assert_allclose(v_act, v_exp, atol=1e-2)

    # check unitary
    np.testing.assert_allclose(v, v_act / (x*y*z), atol=1e-6)
项目:indigo    作者:mbdriscoll    | 项目源码 | 文件源码
def test_csr_matrix(backend, M, N, K, density):
    b = backend()
    c = np.dtype('complex64')
    A = indigo.util.randM(M, N, density)
    A_d = b.csr_matrix(b, A)

    # forward
    x = (np.random.rand(N,K) + 1j * np.random.rand(N,K))
    x = np.require(x, dtype=c, requirements='F')
    y_exp = A.astype(c) * x
    x_d = b.copy_array(x)
    y_d = b.zero_array(y_exp.shape, x.dtype)
    A_d.forward(y_d, x_d)
    y_act = y_d.to_host()
    np.testing.assert_allclose(y_exp, y_act, atol=1e-5)

    # adjoint
    x = (np.random.rand(M,K) + 1j * np.random.rand(M,K))
    x = np.require(x, dtype=c, requirements='C')
    y_exp = A.H.astype(c) * x
    x_d = b.copy_array(x)
    y_d = b.zero_array(y_exp.shape, x.dtype)
    A_d.adjoint(y_d, x_d)
    y_act = y_d.to_host()
    np.testing.assert_allclose(y_exp, y_act, atol=1e-5)
项目:indigo    作者:mbdriscoll    | 项目源码 | 文件源码
def test_blas_axpby(backend, n, alpha, alpha_i, beta):
    b = backend()
    x = (np.random.rand(n) + 1j * np.random.rand(n))
    y = (np.random.rand(n) + 1j * np.random.rand(n))
    x = np.require(x, dtype=np.dtype('complex64'), requirements='F')
    y = np.require(y, dtype=np.dtype('complex64'), requirements='F')
    x_d = b.copy_array(x)
    y_d = b.copy_array(y)

    alpha = alpha + 1j*alpha_i

    y_exp = beta*y + alpha*x
    b.axpby(beta, y_d, alpha, x_d)

    y_act = y_d.to_host()

    np.testing.assert_allclose(y_exp, y_act, atol=1e-6)
项目:pyem    作者:asarnow    | 项目源码 | 文件源码
def write(fname, data, psz=1, origin=None, fast=False):
    """ Writes a MRC file. The header will be blank except for nx,ny,nz,datatype=2 for float32. 
    data should be (nx,ny,nz), and will be written in Fortran order as MRC requires."""
    header = np.zeros(256, dtype=np.int32)  # 1024 byte header
    header_f = header.view(np.float32)
    header[:3] = data.shape  # nx, ny, nz
    header[3] = 2  # mode, 2 = float32 datatype
    header[7:10] = data.shape  # mx, my, mz (grid size)
    header_f[10:13] = [psz * i for i in data.shape]  # xlen, ylen, zlen
    header_f[13:16] = 90.0  # CELLB
    header[16:19] = [1, 2, 3]  # axis order
    if not fast:
        header_f[19:22] = [data.min(), data.max(), data.mean()]  # data stats
    if origin is None:
        header_f[49:52] = [0, 0, 0]
    elif origin is "center":
        header_f[49:52] = [psz * i / 2 for i in data.shape]
    else:
        header_f[49:52] = origin
    header[52] = 542130509  # 'MAP ' chars
    header[53] = 16708
    with open(fname, 'wb') as f:
        header.tofile(f)
        np.require(np.reshape(data, (-1,), order='F'), dtype=np.float32).tofile(f)
项目:pyem    作者:asarnow    | 项目源码 | 文件源码
def append(fname, data):
    with open(fname, 'r+b') as f:
        nx, ny, nz = np.fromfile(f, dtype=np.int32, count=3)  # First 12 bytes of stack.
        f.seek(36)  # First byte of zlen.
        zlen = np.fromfile(f, dtype=np.float32, count=1)
        if data.shape[0] != nx or data.shape[1] != ny:
            raise Exception
        f.seek(0, os.SEEK_END)
        np.require(np.reshape(data, (-1,), order='F'), dtype=np.float32).tofile(f)
        # Update header after new data is written.
        apix = zlen / nz
        nz += data.shape[2]
        zlen += apix * data.shape[2]
        f.seek(8)
        nz.tofile(f)
        f.seek(36)
        zlen.tofile(f)
项目:DeepLearning    作者:corecai163    | 项目源码 | 文件源码
def deprocess_net_image(image):
    image = image.copy()    # use copy don't modify destructively
    image = image[::-1]     # BGR to RGB
    image = image.transpose(1,2,0) # CHW to HCW
    image += [123,117,104]  # undo mean subtraction

    # clamp values in [0,255]
    image[image < 0], image[image > 255] = 0 , 255

    # round and cast form float32 to uint8
    image = np.round(image)
    image = np.require(image,dtype=np.uint8)

    return image

# Load the 1000 ImageNet labels from 
# ilsvrc12/synset_words.txt, and the 5 style labels from finetune_flickr_style/style_names.txt.

# Load ImageNet labels to imagenet_labels
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def _KeenerMatrix(self, A, C, regularization, func, epsilon):
        """func is a regularization function imposed on every element of matrix.
        """
        # Apply Laplace Law
        B = A+A.T+2;
        A = A+1
        A = A/B
        # Regularization
        if func is not None:
            h = np.frompyfunc(func, 1, 1)
            A = np.require(h(A), dtype=np.float32)
        # divide by contest number
        C = C+C.T
        c = np.sum(C, axis=1)
        if regularization:
            A = A/np.expand_dims(c, axis=1)
        A[C==0]=0
        if epsilon is not None:
            A += epsilon*np.ones(A.shape, A.dtype)
        return A
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def __init__(self, table=None, filename=''):
        """
        table:      the pandas DataFrame that records rankable objects competition
                    record
        filename:   the hdf5 filename that stores the DataFrame. The DataFrame
                    must be indexed by 'item_pair_rate'.
        """
        if table is None:
            table = pd.read_hdf(filename, "item_pair_rate")
        table = table[['primary','secondary','rate1','rate2','weight']]
        self.table = table
        # itemid to index table
        idx = self._extract_list(self.table)
        self.itemlist = idx
        temptable = table.iloc[:,:2].values
        pair = np.fromfunction(np.vectorize(lambda i, j: idx[temptable[i,j]]),
                        temptable.shape)
        pair = np.require(pair, dtype=np.int32)
        self.pair = pair
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def RateDifferenceVoteMatrix(self):
        """This function outputs only Point Difference Matrix.
        It can be ensured that every element of the matrix are not less than 0
        """
        idx = self.itemlist
        table = self.table

        icnt = len(idx)
        # allocate space for computing
        D = np.zeros((icnt, icnt), dtype=np.float32)
        pair = self.pair

        fast_rate_diff_vote_matrix_build(pair,
                        np.require(table.iloc[:,2:].values, dtype=np.float32),
                        D)

        return D
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def SimpleDifferenceVoteMatrix(self):
        """This function outputs only Simple Difference Vote Matrix.
        """
        idx = self.itemlist
        table = self.table

        icnt = len(idx)
        # allocate space for computing
        D = np.zeros((icnt, icnt), dtype=np.float32)
        pair = self.pair

        fast_simple_diff_vote_matrix_build(pair,
                        np.require(table.iloc[:,2:].values, dtype=np.float32),
                        D)

        return D
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def RateVoteMatrix(self):
        """This function outputs only Simple Difference Vote Matrix.
        """
        idx = self.itemlist
        table = self.table

        icnt = len(idx)
        # allocate space for computing
        D = np.zeros((icnt, icnt), dtype=np.float32)
        pair = self.pair

        fast_rate_vote_matrix_build(pair,
                        np.require(table.iloc[:,2:].values, dtype=np.float32),
                        D)

        return D
项目:ranking    作者:wattlebird    | 项目源码 | 文件源码
def MasseyVector(self):
        """This function produces X'Wy
        """
        idx = self.itemlist
        table = self.table
        pair = self.pair
        j = np.ravel(pair)
        i = np.repeat(np.arange(table.shape[0], dtype=np.int32), 2, axis=0)
        data = np.array([[1,-1]],dtype=np.float32)
        data = np.ravel(np.repeat(data, table.shape[0], axis=0))
        X = coo_matrix((data, (i, j)), shape=(table.shape[0], len(idx)))
        X = X.tocsr()
        W = np.require(table.iloc[:,4].values, np.float32)
        y = table.iloc[:, 2].values - table.iloc[:, 3].values;
        Wy=np.multiply(W, y)
        return X.T*Wy
项目:risk-slim    作者:ustunb    | 项目源码 | 文件源码
def isIntegral(solution):
        return np.all(solution == np.require(solution, dtype = 'int_'))
项目:risk-slim    作者:ustunb    | 项目源码 | 文件源码
def filter(self, filter_ind):
        filter_ind = np.require(filter_ind, dtype = 'bool')
        new = self.copy()
        new.objvals = self.objvals[filter_ind]
        new.solutions = self.solutions[filter_ind]
        return new
项目:risk-slim    作者:ustunb    | 项目源码 | 文件源码
def generate_binary_data(n_rows = 1000000, n_cols = 20):
    X = np.random.randint(low=0, high=2, size=(n_rows, n_cols))
    Y = np.random.randint(low=0, high=2, size=(n_rows, 1))
    pos_ind = Y == 1
    Y[~pos_ind] = -1
    Z = X * Y
    Z = np.require(Z, requirements=['F'], dtype=np.float64)
    return Z
项目:risk-slim    作者:ustunb    | 项目源码 | 文件源码
def generate_integer_model(n_cols = 20, rho_ub = 100, rho_lb = -100, sparse_pct = 0.5):
    rho = np.random.randint(low=rho_lb, high=rho_ub, size=n_cols)
    rho = np.require(rho, dtype=Z.dtype, requirements=['F'])
    nnz_count = int(sparse_pct * np.floor(n_cols / 2))
    set_to_zero = np.random.choice(range(0, n_cols), size=nnz_count, replace=False)
    rho[set_to_zero] = 0.0
    return rho
项目:risk-slim    作者:ustunb    | 项目源码 | 文件源码
def is_integer(rho):
    """
    checks if numpy array is an integer vector

    Parameters
    ----------
    rho

    Returns
    -------

    """
    return np.array_equal(rho, np.require(rho, dtype=np.int_))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def set_and_check_flag(self, flag, dtype, arr):
        if dtype is None:
            dtype = arr.dtype
        b = np.require(arr, dtype, [flag])
        assert_(b.flags[flag])
        assert_(b.dtype == dtype)

        # a further call to np.require ought to return the same array
        # unless OWNDATA is specified.
        c = np.require(b, None, [flag])
        if flag[0] != 'O':
            assert_(c is b)
        else:
            assert_(c.flags[flag])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def test_unknown_requirement(self):
        a = self.generate_all_false('f8')
        assert_raises(KeyError, np.require, a, None, 'Q')
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def test_non_array_input(self):
        a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
        assert_(a.flags['O'])
        assert_(a.flags['C'])
        assert_(a.flags['A'])
        assert_(a.dtype == 'i4')
        assert_equal(a, [1, 2, 3, 4])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def test_C_and_F_simul(self):
        a = self.generate_all_false('f8')
        assert_raises(ValueError, np.require, a, None, ['C', 'F'])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def test_ensure_array(self):
        class ArraySubclass(np.ndarray):
            pass

        a = ArraySubclass((2, 2))
        b = np.require(a, None, ['E'])
        assert_(type(b) is np.ndarray)
项目:TPN    作者:myfavouritekk    | 项目源码 | 文件源码
def _gt_propagate_boxes(boxes, annot_proto, frame_id, window, overlap_thres):
    pred_boxes = []
    annots = []
    for annot in annot_proto['annotations']:
        for idx, box in enumerate(annot['track']):
            if box['frame'] == frame_id:
                gt1 = box['bbox']
                deltas = []
                deltas.append(gt1)
                for offset in xrange(1, window):
                    try:
                        gt2 = annot['track'][idx+offset]['bbox']
                    except IndexError:
                        gt2 = gt1
                    delta = bbox_transform(np.asarray([gt1]), np.asarray([gt2]))
                    deltas.append(delta)
                annots.append(deltas)
    gt1s = [annot[0] for annot in annots]
    if not gt1s:
        # no grount-truth, boxes remain still
        return np.tile(np.asarray(boxes)[:,np.newaxis,:], [1,window-1,1])
    overlaps = bbox_overlaps(np.require(boxes, dtype=np.float),
                             np.require(gt1s, dtype=np.float))
    assert len(overlaps) == len(boxes)
    for gt_overlaps, box in zip(overlaps, boxes):
        max_overlap = np.max(gt_overlaps)
        max_gt = np.argmax(gt_overlaps)
        sequence_box = []
        if max_overlap < overlap_thres:
            for offset in xrange(1, window):
                sequence_box.append(box)
        else:
            for offset in xrange(1, window):
                delta = annots[max_gt][offset]
                sequence_box.append(
                    bbox_transform_inv(np.asarray([box]), delta)[0].tolist())
        pred_boxes.append((sequence_box))
    return np.asarray(pred_boxes)
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
def _setup_arrays(x,v,m,omega=None):
    sindx= numpy.argsort(x)
    # Keep track of amount of mass above and below and compute acceleration
    mass_below= numpy.cumsum(m[sindx])
    mass_below[-1]= 0.
    mass_below= numpy.roll(mass_below,1)
    mass_above= numpy.cumsum(m[sindx][::-1])[::-1]
    mass_above[0]= 0.
    mass_above= numpy.roll(mass_above,-1)
    a= (mass_above-mass_below)[numpy.argsort(sindx)]
    # Solve for all collisions, using C code for consistency
    tcoll= []
    for xi,vi,ai,xii,vii,aii in zip(x[sindx][:-1],v[sindx][:-1],a[sindx][:-1],
                                    x[sindx][1:],v[sindx][1:],a[sindx][1:]):
        if omega is None:
            tcoll.append(_wendy_solve_coll_quad_func(xi-xii,vi-vii,(ai-aii)/2.))
        else:
            tcoll.append(_wendy_solve_coll_harm_func(xi-xii,vi-vii,ai-aii,omega))
    tcoll= numpy.array(tcoll)
    cindx= ctypes.c_int(numpy.argmin(tcoll))
    next_tcoll= ctypes.c_double(tcoll[cindx])
    # Prepare for C
    err= ctypes.c_int(0)
    #Array requirements
    x= numpy.require(x,dtype=numpy.float64,requirements=['C','W'])
    v= numpy.require(v,dtype=numpy.float64,requirements=['C','W'])
    a= numpy.require(a,dtype=numpy.float64,requirements=['C','W'])
    m= numpy.require(m,dtype=numpy.float64,requirements=['C','W'])
    sindx= numpy.require(sindx,dtype=numpy.int32,requirements=['C','W'])
    tcoll= numpy.require(tcoll,dtype=numpy.float64,requirements=['C','W'])
    return (x,v,m,a,sindx,cindx,next_tcoll,tcoll,err)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def calculate(self, parameters_dict):
        """Calculate DKI statistics like the mean, axial and radial kurtosis.

        The Mean Kurtosis (MK) is calculated by averaging the Kurtosis over orientations on the unit sphere.
        The Axial Kurtosis (AK) is obtained using the principal direction of diffusion (fe; first eigenvec)
        from the Tensor as its direction and then averaging the Kurtosis over +fe and -fe.
        Finally, the Radial Kurtosis (RK) is calculated by averaging the Kurtosis over a circle of directions around
        the first eigenvec.

        Args:
            parameters_dict (dict): the fitted Kurtosis parameters, this requires a dictionary with at least
                the elements:
                'd', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'W_0000', 'W_1000', 'W_1100', 'W_1110',
                'W_1111', 'W_2000', 'W_2100', 'W_2110', 'W_2111', 'W_2200', 'W_2210', 'W_2211',
                'W_2220', 'W_2221', 'W_2222'.

        Returns:
            dict: maps for the Mean Kurtosis (MK), Axial Kurtosis (AK) and Radial Kurtosis (RK).
        """
        if parameters_dict['d'].dtype == np.float32:
            np_dtype = np.float32
            mot_float_type = SimpleCLDataType.from_string('float')
            double_precision = False
        else:
            np_dtype = np.float64
            mot_float_type = SimpleCLDataType.from_string('double')
            double_precision = True

        param_names = ['d', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'W_0000', 'W_1000', 'W_1100', 'W_1110',
                       'W_1111', 'W_2000', 'W_2100', 'W_2110', 'W_2111', 'W_2200', 'W_2210', 'W_2211',
                       'W_2220', 'W_2221', 'W_2222']
        parameters = np.require(np.column_stack([parameters_dict[n] for n in param_names]),
                                np_dtype, requirements=['C', 'A', 'O'])
        directions = convert_data_to_dtype(self._get_spherical_samples(), 'mot_float_type4', mot_float_type)
        return self._calculate(parameters, param_names, directions, double_precision)
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def required(ob):
    """Return an object that meets Shapely requirements for self-owned
    C-continguous data, copying if necessary, or just return the original
    object."""
    if has_numpy and hasattr(ob, '__array_interface__'):
        return numpy.require(ob, numpy.float64, ["C", "OWNDATA"])
    else:
        return ob
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def set_and_check_flag(self, flag, dtype, arr):
        if dtype is None:
            dtype = arr.dtype
        b = np.require(arr, dtype, [flag])
        assert_(b.flags[flag])
        assert_(b.dtype == dtype)

        # a further call to np.require ought to return the same array
        # unless OWNDATA is specified.
        c = np.require(b, None, [flag])
        if flag[0] != 'O':
            assert_(c is b)
        else:
            assert_(c.flags[flag])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def test_unknown_requirement(self):
        a = self.generate_all_false('f8')
        assert_raises(KeyError, np.require, a, None, 'Q')
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def test_non_array_input(self):
        a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
        assert_(a.flags['O'])
        assert_(a.flags['C'])
        assert_(a.flags['A'])
        assert_(a.dtype == 'i4')
        assert_equal(a, [1, 2, 3, 4])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def test_C_and_F_simul(self):
        a = self.generate_all_false('f8')
        assert_raises(ValueError, np.require, a, None, ['C', 'F'])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def test_ensure_array(self):
        class ArraySubclass(np.ndarray):
            pass

        a = ArraySubclass((2, 2))
        b = np.require(a, None, ['E'])
        assert_(type(b) is np.ndarray)
项目:cebl    作者:idfah    | 项目源码 | 文件源码
def slidingWindow(s, span, stride=None, axis=0):
    """Sliding window.
    """
    #s = np.ascontiguousarray(s)
    s = np.require(s, requirements=['C', 'O'])

    if stride is None:
        stride = span

    # catch some bad values since this is a common place for
    # bugs to crop up in other routines
    if span > s.shape[axis]:
        raise ValueError('Span of %d exceeds input length of %d.' % (span, s.shape[axis]))

    if span < 0:
        raise ValueError('Negative span of %d is invalid.' % span)

    if stride < 1:
        raise ValueError('Stride of %d is not positive.' % stride)

    nWin = int(np.ceil((s.shape[axis]-span+1) / float(stride)))

    shape = list(s.shape)
    shape[axis] = span
    shape.insert(axis, nWin)

    strides = list(s.strides)
    strides.insert(axis, stride*strides[axis])

    return npst.as_strided(s, shape=shape, strides=strides)
项目:cebl    作者:idfah    | 项目源码 | 文件源码
def train(self, x, g, optimFunc, **kwargs):
        x = util.segmat(x)
        x = np.require(x, requirements=['O', 'C'])

        g = util.segmat(g)
        g = np.require(g, requirements=['O', 'C'])

        self.trainResult = optimFunc(self, x=x, g=g, **kwargs)
项目:cebl    作者:idfah    | 项目源码 | 文件源码
def train(self, classData, optimFunc, **kwargs):
        x, g = label.indicatorsFromList(classData)
        x = np.require(x, requirements=['O', 'C'])
        self.trainResult = optimFunc(self, x=x, g=g, **kwargs)
项目:cebl    作者:idfah    | 项目源码 | 文件源码
def train(self, classData, optimFunc, **kwargs):
        x, g = label.indicatorsFromList(classData)
        x = np.require(x, requirements=['O', 'C'])
        self.trainResult = optimFunc(self, x=x, g=g, **kwargs)

        #dv = self.discrim(x, accum='mult')
        #self.normSoftmaxMean = dv.mean()
        #self.normSoftmaxStd = dv.std()
        #self.normSoftmaxMin = dv.min()
        #self.normSoftmaxMax = (dv-self.normSoftmaxMin).max()
项目:heliopy    作者:heliopython    | 项目源码 | 文件源码
def _bad_tt2000(*args, **kwargs):
        """Convenience function for complaining that TT2000 not supported"""
        raise NotImplementedError(
            'TT2000 functions require CDF library 3.4.0 or later')
项目:heliopy    作者:heliopython    | 项目源码 | 文件源码
def convert_input_array(self, buffer):
        """Converts a buffer of raw data from this slice

        EPOCH(16) variables always need to be converted.
        CHAR need converted to Unicode if py3k

        Parameters
        ==========
        buffer : numpy.array
            data as read from the CDF file

        Returns
        =======
        out : numpy.array
            converted data
        """
        result = self._flip_array(buffer)

        #Convert to derived types
        cdftype = self.zvar.type()
        if not self.zvar._raw:
            if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value) and \
                    str != bytes:
                dt = numpy.dtype('U{0}'.format(result.dtype.itemsize))
                result = numpy.require(numpy.char.array(result).decode(),
                                       dtype=dt)
            elif cdftype == const.CDF_EPOCH.value:
                result = lib.v_epoch_to_datetime(result)
            elif cdftype == const.CDF_EPOCH16.value:
                result = lib.v_epoch16_to_datetime(result)
            elif cdftype == const.CDF_TIME_TT2000.value:
                result = lib.v_tt2000_to_datetime(result)
        return result