python类require()的实例源码

test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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])
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_unknown_requirement(self):
        a = self.generate_all_false('f8')
        assert_raises(KeyError, np.require, a, None, 'Q')
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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])
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_C_and_F_simul(self):
        a = self.generate_all_false('f8')
        assert_raises(ValueError, np.require, a, None, ['C', 'F'])
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
propagate.py 文件源码 项目:TPN 作者: myfavouritekk 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:wendy 作者: jobovy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
dki_measures.py 文件源码 项目:MDT 作者: cbclab 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
coords.py 文件源码 项目:Vector-Tiles-Reader-QGIS-Plugin 作者: geometalab 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
test_numeric.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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])
test_numeric.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_unknown_requirement(self):
        a = self.generate_all_false('f8')
        assert_raises(KeyError, np.require, a, None, 'Q')
test_numeric.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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])
test_numeric.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_C_and_F_simul(self):
        a = self.generate_all_false('f8')
        assert_raises(ValueError, np.require, a, None, ['C', 'F'])
test_numeric.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
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)
embed.py 文件源码 项目:cebl 作者: idfah 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
convreg.py 文件源码 项目:cebl 作者: idfah 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
conv.py 文件源码 项目:cebl 作者: idfah 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
convac.py 文件源码 项目:cebl 作者: idfah 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
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()
__init__.py 文件源码 项目:heliopy 作者: heliopython 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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')
__init__.py 文件源码 项目:heliopy 作者: heliopython 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号