当前位置: 首页>>代码示例>>Python>>正文


Python numpy.diff方法代码示例

本文整理汇总了Python中numpy.diff方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.diff方法的具体用法?Python numpy.diff怎么用?Python numpy.diff使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.diff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _bounds_from_array

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _bounds_from_array(arr, dim_name, bounds_name):
    """Get the bounds of an array given its center values.

    E.g. if lat-lon grid center lat/lon values are known, but not the
    bounds of each grid box.  The algorithm assumes that the bounds
    are simply halfway between each pair of center values.
    """
    # TODO: don't assume needed dimension is in axis=0
    # TODO: refactor to get rid of repetitive code
    spacing = arr.diff(dim_name).values
    lower = xr.DataArray(np.empty_like(arr), dims=arr.dims,
                         coords=arr.coords)
    lower.values[:-1] = arr.values[:-1] - 0.5*spacing
    lower.values[-1] = arr.values[-1] - 0.5*spacing[-1]
    upper = xr.DataArray(np.empty_like(arr), dims=arr.dims,
                         coords=arr.coords)
    upper.values[:-1] = arr.values[:-1] + 0.5*spacing
    upper.values[-1] = arr.values[-1] + 0.5*spacing[-1]
    bounds = xr.concat([lower, upper], dim='bounds')
    return bounds.T 
开发者ID:spencerahill,项目名称:aospy,代码行数:22,代码来源:model.py

示例2: get_stages_from_blocks

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def get_stages_from_blocks(self, widths):
        """Gets widths/stage_blocks of network at each stage.

        Args:
            widths (list[int]): Width in each stage.

        Returns:
            tuple(list): width and depth of each stage
        """
        width_diff = [
            width != width_prev
            for width, width_prev in zip(widths + [0], [0] + widths)
        ]
        stage_widths = [
            width for width, diff in zip(widths, width_diff[:-1]) if diff
        ]
        stage_blocks = np.diff([
            depth for depth, diff in zip(range(len(width_diff)), width_diff)
            if diff
        ]).tolist()
        return stage_widths, stage_blocks 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:23,代码来源:regnet.py

示例3: splrep

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def splrep(coordinates, t, order, weights, smoothing, periodic):
        from scipy import interpolate
        (x,y) = coordinates
        # we need to skip anything where t[i] and t[i+1] are too close
        wh = np.where(np.isclose(np.diff(t), 0))[0]
        if len(wh) > 0:
            (t,x,y) = [np.array(u) for u in (t,x,y)]
            ii = np.arange(len(t))
            for i in reversed(wh):
                ii[i+1:-1] = ii[i+2:]
                for u in (t,x,y):
                    u[i] = np.mean(u[i:i+2])
            ii = ii[:-len(wh)]
            (t,x,y) = [u[ii] for u in (t,x,y)]
        xtck = interpolate.splrep(t, x, k=order, s=smoothing, w=weights, per=periodic)
        ytck = interpolate.splrep(t, y, k=order, s=smoothing, w=weights, per=periodic)
        return tuple([tuple([pimms.imm_array(u) for u in tck])
                      for tck in (xtck,ytck)]) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:20,代码来源:core.py

示例4: subcurve

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def subcurve(self, t0, t1):
        '''
        curve.subcurve(t0, t1) yields a curve-spline object that is equivalent to the given
          curve but that extends from curve(t0) to curve(t1) only.
        '''
        # if t1 is less than t0, then we want to actually do this in reverse...
        if t1 == t0: raise ValueError('Cannot take subcurve of a point')
        if t1 < t0:
            tt = self.curve_length()
            return self.reverse().subcurve(tt - t0, tt - t1)
        idx = [ii for (ii,t) in enumerate(self.t) if t0 < t and t < t1]
        pt0 = self(t0)
        pt1 = self(t1)
        coords = np.vstack([[pt0], self.coordinates.T[idx], [pt1]])
        ts = np.concatenate([[t0], self.t[idx], [t1]])
        dists  = None if self.distances is None else np.diff(ts)
        return CurveSpline(
            coords.T,
            order=self.order,
            smoothing=self.smoothing,
            periodic=False,
            distances=dists,
            meta_data=self.meta_data) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:25,代码来源:core.py

示例5: test_cmag

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def test_cmag(self):
        '''
        test_cmag() ensures that the neuropythy.vision cortical magnification function is working.
        '''
        import neuropythy.vision as vis
        logging.info('neuropythy: Testing areal cortical magnification...')
        dset = ny.data['benson_winawer_2018']
        sub = dset.subjects['S1202']
        hem = [sub.lh, sub.rh][np.random.randint(2)]
        cm = vis.areal_cmag(hem.midgray_surface, 'prf_',
                            mask=('inf-prf_visual_area', 1),
                            weight='prf_variance_explained')
        # cmag should get smaller in general
        ths = np.arange(0, 2*np.pi, np.pi/3)
        es = [0.5, 1, 2, 4]
        x = np.diff([np.mean(cm(e*np.cos(ths), e*np.sin(ths))) for e in es])
        self.assertTrue((x < 0).all()) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:19,代码来源:__init__.py

示例6: mask_to_rle

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def mask_to_rle(img, mask_value=255, transpose=True):
    img = np.int32(img)
    if transpose:
      img = img.T
    img = img.flatten()
    img[img == mask_value] = 1
    pimg = np.pad(img, 1, mode='constant')
    diff = np.diff(pimg)
    starts = np.where(diff == 1)[0]
    ends = np.where(diff == -1)[0]
    rle = []
    previous_end = 0
    for start, end in zip(starts, ends):
      relative_start = start - previous_end
      length = end - start
      previous_end = end
      rle.append(str(relative_start))
      rle.append(str(length))
    if len(rle) == 0:
      return "-1"
    return " ".join(rle) 
开发者ID:see--,项目名称:kuzushiji-recognition,代码行数:23,代码来源:data.py

示例7: test_gen_sma

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def test_gen_sma(self):
        r"""Test gen_sma method.

        Approach: Ensures the output is set, of the correct type, length, and units.
        Check that they are in the correct range and follow the distribution.
        """

        plan_pop = self.fixture
        n = 10000
        sma = plan_pop.gen_sma(n)

        # ensure the units are length
        self.assertEqual((sma/u.km).decompose().unit, u.dimensionless_unscaled)
        # sma > 0
        self.assertTrue(np.all(sma.value >= 0))
        # sma >= arange[0], sma <= arange[1]
        self.assertTrue(np.all(sma - plan_pop.arange[0] >= 0))
        self.assertTrue(np.all(plan_pop.arange[1] - sma >= 0))

        h = np.histogram(sma.to('AU').value,100,density=True)
        hx = np.diff(h[1])/2.+h[1][:-1]
        hp = plan_pop.dist_sma(hx)

        chi2 = scipy.stats.chisquare(h[0],hp)
        self.assertGreaterEqual(chi2[1],0.95) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:27,代码来源:test_KeplerLike2.py

示例8: test_gen_plan_params

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def test_gen_plan_params(self):
        r"""Test generated planet parameters:
        Expected: all 1 R_E, all p = 0.67, e = 0, and uniform a in arange
        """

        obj = EarthTwinHabZone1(**self.spec)

        x = 10000

        a, e, p, Rp = obj.gen_plan_params(x)
        
        assert(np.all(e == 0))
        assert(np.all(p == 0.367))
        assert(np.all(Rp == 1.0*u.R_earth))

        h = np.histogram(a.to('AU').value,100,density=True)
        chi2 = scipy.stats.chisquare(h[0],[1.0/np.diff(obj.arange.to('AU').value)[0]]*len(h[0]))
        self.assertGreater(chi2[1], 0.95) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:20,代码来源:test_EarthTwinHabZone1.py

示例9: test_gen_plan_params

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def test_gen_plan_params(self):
        r"""Test generated planet parameters:
        Expected: all 1 R_E, all p = 0.67, e = 0, and uniform a,e in arange,erange
        """

        obj = EarthTwinHabZone2(constrainOrbits=False,erange=[0.1,0.5],**self.spec)

        x = 10000

        a, e, p, Rp = obj.gen_plan_params(x)
        
        assert(np.all(p == 0.367))
        assert(np.all(Rp == 1.0*u.R_earth))

        for param,param_range in zip([a.value,e],[obj.arange.value,obj.erange]):
            h = np.histogram(param,100,density=True)
            chi2 = scipy.stats.chisquare(h[0],[1.0/np.diff(param_range)[0]]*len(h[0]))
            self.assertGreater(chi2[1], 0.95) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:20,代码来源:test_EarthTwinHabZone2.py

示例10: test_simpSample_trivial

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def test_simpSample_trivial(self):
        """ Test simple rejection sampler with trivial inputs

        Test method: set up sampling with equal upper and lower bounds
        """
        
        ulim = [0,1]
        ufun = lambda x: 1.0/np.diff(ulim)

        n = 10000
        
        for mod in self.mods:
            print('Testing trivial input for sampler: %s'%mod.__name__)
            sampler = mod(ufun,0.5,0.5)
            sample = sampler(n)
            
            self.assertEqual(len(sample),n,'Sampler %s does not return all same value'%mod.__name__)
            self.assertTrue(np.all(sample == 0.5),'Sampler %s does not return all values at 0.5'%mod.__name__) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:20,代码来源:test_Samplers.py

示例11: _ecg_rsa_cycles

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _ecg_rsa_cycles(signals):
    """Extract respiratory cycles."""
    inspiration_onsets = np.intersect1d(
        np.where(signals["RSP_Phase"] == 1)[0], np.where(signals["RSP_Phase_Completion"] == 0)[0], assume_unique=True
    )

    expiration_onsets = np.intersect1d(
        np.where(signals["RSP_Phase"] == 0)[0], np.where(signals["RSP_Phase_Completion"] == 0)[0], assume_unique=True
    )

    cycles_length = np.diff(inspiration_onsets)

    return {
        "RSP_Inspiration_Onsets": inspiration_onsets,
        "RSP_Expiration_Onsets": expiration_onsets,
        "RSP_Cycles_Length": cycles_length,
    } 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:19,代码来源:ecg_rsa.py

示例12: _ecg_findpeaks_pantompkins

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _ecg_findpeaks_pantompkins(signal, sampling_rate=1000):
    """From https://github.com/berndporr/py-ecg-detectors/

    - Jiapu Pan and Willis J. Tompkins. A Real-Time QRS Detection Algorithm.
    In: IEEE Transactions on Biomedical Engineering BME-32.3 (1985), pp. 230–236.

    """
    diff = np.diff(signal)

    squared = diff * diff

    N = int(0.12 * sampling_rate)
    mwa = _ecg_findpeaks_MWA(squared, N)
    mwa[: int(0.2 * sampling_rate)] = 0

    mwa_peaks = _ecg_findpeaks_peakdetect(mwa, sampling_rate)

    mwa_peaks = np.array(mwa_peaks, dtype="int")
    return mwa_peaks


# =============================================================================
# Hamilton (2002)
# ============================================================================= 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:26,代码来源:ecg_findpeaks.py

示例13: _rsp_findpeaks_biosppy

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _rsp_findpeaks_biosppy(rsp_cleaned, sampling_rate):

    extrema = _rsp_findpeaks_extrema(rsp_cleaned)
    extrema, amplitudes = _rsp_findpeaks_outliers(rsp_cleaned, extrema, amplitude_min=0)

    peaks, troughs = _rsp_findpeaks_sanitize(extrema, amplitudes)

    # Apply minimum period outlier-criterion (exclude inter-breath-intervals
    # that produce breathing rate larger than 35 breaths per minute.
    outlier_idcs = np.where((np.diff(peaks) / sampling_rate) < 1.7)[0]

    peaks = np.delete(peaks, outlier_idcs)
    troughs = np.delete(troughs, outlier_idcs)

    info = {"RSP_Peaks": peaks, "RSP_Troughs": troughs}
    return info 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:18,代码来源:rsp_findpeaks.py

示例14: _eog_clean_kong1998

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _eog_clean_kong1998(eog_signal, sampling_rate=1000):
    """Kong, X., & Wilson, G.

    F. (1998). A new EOG-based eyeblink detection algorithm. Behavior Research Methods, Instruments, & Computers,
    30(4), 713-719.

    """
    #  The order E should be less than half of the expected eyeblink duration. For example, if
    # the expected blink duration is 200 msec (10 samples with a sampling rate of 50 Hz), the
    # order E should be less than five samples.
    eroded = scipy.ndimage.grey_erosion(eog_signal, size=int((0.2 / 2) * sampling_rate))

    # a "low-noise" Lanczos differentiation filter introduced in Hamming (1989) is employed.
    # Frequently, a first order differentiation filter is sufficient and has the familiar
    # form of symmetric difference:
    # w[k] = 0.5 * (y[k + 1] - y[k - 1])
    diff = eroded - np.concatenate([[0], 0.5 * np.diff(eroded)])

    # To reduce the effects of noise, characterized by small fluctuations around zero, a
    # median filter is also used with the order of the median filter denoted as M.
    # The median filter acts like a mean filter except that it preserves the sharp edges ofthe
    # input. The order M should be less than a quarter ofthe expected eyeblink duration.
    clean = scipy.ndimage.median_filter(diff, size=int((0.2 / 4) * sampling_rate))

    return clean 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:27,代码来源:eog_clean.py

示例15: _hrv_get_rri

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diff [as 别名]
def _hrv_get_rri(peaks=None, sampling_rate=1000, interpolate=False, **kwargs):

    rri = np.diff(peaks) / sampling_rate * 1000

    if interpolate is False:
        return rri

    else:

        # Minimum sampling rate for interpolation
        if sampling_rate < 10:
            sampling_rate = 10

        # Compute length of interpolated heart period signal at requested sampling rate.
        desired_length = int(np.rint(peaks[-1] / sampling_rate * sampling_rate))

        rri = signal_interpolate(
            peaks[1:],  # Skip first peak since it has no corresponding element in heart_period
            rri,
            x_new=np.arange(desired_length),
            **kwargs
        )
        return rri, sampling_rate 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:25,代码来源:hrv_utils.py


注:本文中的numpy.diff方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。