scipy库 signal 导入_Python scipy.signal方法代码示例

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

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

示例1: add_delta_deltas

​点赞 7

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def add_delta_deltas(filterbanks, name=None):

"""Compute time first and second-order derivative channels.

Args:

filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1]

name: scope name

Returns:

float32 tensor with shape [batch_size, len, num_bins, 3]

"""

delta_filter = np.array([2, 1, 0, -1, -2])

delta_delta_filter = scipy.signal.convolve(delta_filter, delta_filter, "full")

delta_filter_stack = np.array(

[[0] * 4 + [1] + [0] * 4, [0] * 2 + list(delta_filter) + [0] * 2,

list(delta_delta_filter)],

dtype=np.float32).T[:, None, None, :]

delta_filter_stack /= np.sqrt(

np.sum(delta_filter_stack**2, axis=0, keepdims=True))

filterbanks = tf.nn.conv2d(

filterbanks, delta_filter_stack, [1, 1, 1, 1], "SAME", data_format="NHWC",

name=name)

return filterbanks

开发者ID:akzaidi,项目名称:fine-lm,代码行数:27,

示例2: extract_chip_samples

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def extract_chip_samples(samples):

a = array(samples)

f = scipy.fft(a*a)

p = find_clock_frequency(abs(f))

if 0 == p:

return []

cycles_per_sample = (p*1.0)/len(f)

clock_phase = 0.25 + numpy.angle(f[p])/(tau)

if clock_phase <= 0.5:

clock_phase += 1

chip_samples = []

for i in range(len(a)):

if clock_phase >= 1:

clock_phase -= 1

chip_samples.append(a[i])

clock_phase += cycles_per_sample

return chip_samples

# input: complex valued samples, FFT bin number of chip rate

# input signal must be centered at 0 frequency

# output: number of chips found in repetitive chip sequence

开发者ID:mossmann,项目名称:clock-recovery,代码行数:23,

示例3: cosine

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def cosine(M):

"""Gernerate a halfcosine window of given length

Uses :code:`scipy.signal.cosine` by default. However since this window

function has only recently been merged into mainline SciPy, a fallback

calculation is in place.

Parameters

----------

M : int

Length of the window.

Returns

-------

data : array_like

The window function

"""

try:

import scipy.signal

return scipy.signal.cosine(M)

except AttributeError:

return numpy.sin(numpy.pi / M * (numpy.arange(0, M) + .5))

开发者ID:nils-werner,项目名称:stft,代码行数:25,

示例4: _ecg_clean_elgendi

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _ecg_clean_elgendi(ecg_signal, sampling_rate=1000):

"""From https://github.com/berndporr/py-ecg-detectors/

- Elgendi, Mohamed & Jonkman, Mirjam & De Boer, Friso. (2010). Frequency Bands Effects on QRS

Detection. The 3rd International Conference on Bio-inspired Systems and Signal Processing

(BIOSIGNALS2010). 428-431.

"""

f1 = 8 / sampling_rate

f2 = 20 / sampling_rate

b, a = scipy.signal.butter(2, [f1 * 2, f2 * 2], btype="bandpass")

return scipy.signal.lfilter(b, a, ecg_signal) # Return filtered

# =============================================================================

# Hamilton (2002)

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:22,

示例5: _ecg_findpeaks_pantompkins

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [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,

示例6: _ecg_delineator_peak_T_offset

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _ecg_delineator_peak_T_offset(rpeak, heartbeat, R, T):

if T is None:

return np.nan

segment = heartbeat.iloc[R + T :] # Select left of P wave

try:

signal = signal_smooth(segment["Signal"].values, size=R / 10)

except TypeError:

signal = segment["Signal"]

if len(signal) < 2:

return np.nan

signal = np.gradient(np.gradient(signal))

T_offset = np.argmax(signal)

return rpeak + T + T_offset

# =============================================================================

# Internals

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:24,

示例7: _resample_pandas

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _resample_pandas(signal, desired_length):

# Convert to Time Series

index = pd.date_range("20131212", freq="L", periods=len(signal))

resampled_signal = pd.Series(signal, index=index)

# Create resampling factor

resampling_factor = str(np.round(1 / (desired_length / len(signal)), 6)) + "L"

# Resample

resampled_signal = resampled_signal.resample(resampling_factor).bfill().values

# Sanitize

resampled_signal = _resample_sanitize(resampled_signal, desired_length)

return resampled_signal

# =============================================================================

# Internals

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:22,

示例8: _signal_filter_savgol

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _signal_filter_savgol(signal, sampling_rate=1000, order=2, window_size="default"):

"""Filter a signal using the Savitzky-Golay method.

Default window size is chosen based on `Sadeghi, M., & Behnia, F. (2018). Optimum window length of

Savitzky-Golay filters with arbitrary order. arXiv preprint arXiv:1808.10489.

`_.

"""

window_size = _signal_filter_windowsize(window_size=window_size, sampling_rate=sampling_rate)

filtered = scipy.signal.savgol_filter(signal, window_length=window_size, polyorder=order)

return filtered

# =============================================================================

# FIR

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:19,

示例9: _signal_filter_butterworth_ba

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _signal_filter_butterworth_ba(signal, sampling_rate=1000, lowcut=None, highcut=None, order=5):

"""Filter a signal using IIR Butterworth B/A method."""

# Get coefficients

freqs, filter_type = _signal_filter_sanitize(lowcut=lowcut, highcut=highcut, sampling_rate=sampling_rate)

b, a = scipy.signal.butter(order, freqs, btype=filter_type, output="ba", fs=sampling_rate)

try:

filtered = scipy.signal.filtfilt(b, a, signal, method="gust")

except ValueError:

filtered = scipy.signal.filtfilt(b, a, signal, method="pad")

return filtered

# =============================================================================

# Bessel

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:19,

示例10: _signal_filter_powerline

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _signal_filter_powerline(signal, sampling_rate, powerline=50):

"""Filter out 50 Hz powerline noise by smoothing the signal with a moving average kernel with the width of one

period of 50Hz."""

if sampling_rate >= 100:

b = np.ones(int(sampling_rate / powerline))

else:

b = np.ones(2)

a = [len(b)]

y = scipy.signal.filtfilt(b, a, signal, method="pad")

return y

# =============================================================================

# Utility

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:18,

示例11: _rsp_clean_khodadad2018

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _rsp_clean_khodadad2018(rsp_signal, sampling_rate=1000):

"""The algorithm is based on (but not an exact implementation of) the "Zero-crossing algorithm with amplitude

threshold" by `Khodadad et al. (2018)

`_.

"""

# Slow baseline drifts / fluctuations must be removed from the raw

# breathing signal (i.e., the signal must be centered around zero) in order

# to be able to reliable detect zero-crossings.

# Remove baseline by applying a lowcut at .05Hz (preserves breathing rates

# higher than 3 breath per minute) and high frequency noise by applying a

# highcut at 3 Hz (preserves breathing rates slower than 180 breath per

# minute).

clean = signal_filter(

rsp_signal, sampling_rate=sampling_rate, lowcut=0.05, highcut=3, order=2, method="butterworth_ba"

)

return clean

# =============================================================================

# BioSPPy

# =============================================================================

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:27,

示例12: _rsp_clean_biosppy

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def _rsp_clean_biosppy(rsp_signal, sampling_rate=1000):

"""Uses the same defaults as `BioSPPy.

`_.

"""

# Parameters

order = 2

frequency = [0.1, 0.35]

frequency = 2 * np.array(frequency) / sampling_rate # Normalize frequency to Nyquist Frequency (Fs/2).

# Filtering

b, a = scipy.signal.butter(N=order, Wn=frequency, btype="bandpass", analog=False)

filtered = scipy.signal.filtfilt(b, a, rsp_signal)

# Baseline detrending

clean = signal_detrend(filtered, order=0)

return clean

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:21,

示例13: test_signal_detrend

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_signal_detrend():

signal = np.cos(np.linspace(start=0, stop=10, num=1000)) # Low freq

signal += np.cos(np.linspace(start=0, stop=100, num=1000)) # High freq

signal += 3 # Add baseline

rez_nk = nk.signal_detrend(signal, order=1)

rez_scipy = scipy.signal.detrend(signal, type="linear")

assert np.allclose(np.mean(rez_nk - rez_scipy), 0, atol=0.000001)

rez_nk = nk.signal_detrend(signal, order=0)

rez_scipy = scipy.signal.detrend(signal, type="constant")

assert np.allclose(np.mean(rez_nk - rez_scipy), 0, atol=0.000001)

# Tarvainen

rez_nk = nk.signal_detrend(signal, method="tarvainen2002", regularization=500)

assert np.allclose(np.mean(rez_nk - signal), -2.88438737697, atol=0.000001)

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:19,

示例14: test_signal_filter

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_signal_filter():

signal = np.cos(np.linspace(start=0, stop=10, num=1000)) # Low freq

signal += np.cos(np.linspace(start=0, stop=100, num=1000)) # High freq

filtered = nk.signal_filter(signal, highcut=10)

assert np.std(signal) > np.std(filtered)

# Generate 10 seconds of signal with 2 Hz oscillation and added 50Hz powerline-noise.

sampling_rate = 250

samples = np.arange(10 * sampling_rate)

signal = np.sin(2 * np.pi * 2 * (samples / sampling_rate))

powerline = np.sin(2 * np.pi * 50 * (samples / sampling_rate))

signal_corrupted = signal + powerline

signal_clean = nk.signal_filter(signal_corrupted, sampling_rate=sampling_rate, method="powerline")

# import matplotlib.pyplot as plt

# figure, (ax0, ax1, ax2) = plt.subplots(nrows=3, ncols=1, sharex=True)

# ax0.plot(signal_corrupted)

# ax1.plot(signal)

# ax2.plot(signal_clean * 100)

assert np.allclose(sum(signal_clean - signal), -2, atol=0.2)

开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:26,

示例15: applyFilter

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def applyFilter(data, b, a, padding=100, bidir=True):

"""Apply a linear filter with coefficients a, b. Optionally pad the data before filtering

and/or run the filter in both directions."""

try:

import scipy.signal

except ImportError:

raise Exception("applyFilter() requires the package scipy.signal.")

d1 = data.view(np.ndarray)

if padding > 0:

d1 = np.hstack([d1[:padding], d1, d1[-padding:]])

if bidir:

d1 = scipy.signal.lfilter(b, a, scipy.signal.lfilter(b, a, d1)[::-1])[::-1]

else:

d1 = scipy.signal.lfilter(b, a, d1)

if padding > 0:

d1 = d1[padding:-padding]

if (hasattr(data, 'implements') and data.implements('MetaArray')):

return MetaArray(d1, info=data.infoCopy())

else:

return d1

开发者ID:SrikanthVelpuri,项目名称:tf-pose,代码行数:27,

示例16: besselFilter

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def besselFilter(data, cutoff, order=1, dt=None, btype='low', bidir=True):

"""return data passed through bessel filter"""

try:

import scipy.signal

except ImportError:

raise Exception("besselFilter() requires the package scipy.signal.")

if dt is None:

try:

tvals = data.xvals('Time')

dt = (tvals[-1]-tvals[0]) / (len(tvals)-1)

except:

dt = 1.0

b,a = scipy.signal.bessel(order, cutoff * dt, btype=btype)

return applyFilter(data, b, a, bidir=bidir)

#base = data.mean()

#d1 = scipy.signal.lfilter(b, a, data.view(ndarray)-base) + base

#if (hasattr(data, 'implements') and data.implements('MetaArray')):

#return MetaArray(d1, info=data.infoCopy())

#return d1

开发者ID:SrikanthVelpuri,项目名称:tf-pose,代码行数:24,

示例17: butterworthFilter

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def butterworthFilter(data, wPass, wStop=None, gPass=2.0, gStop=20.0, order=1, dt=None, btype='low', bidir=True):

"""return data passed through bessel filter"""

try:

import scipy.signal

except ImportError:

raise Exception("butterworthFilter() requires the package scipy.signal.")

if dt is None:

try:

tvals = data.xvals('Time')

dt = (tvals[-1]-tvals[0]) / (len(tvals)-1)

except:

dt = 1.0

if wStop is None:

wStop = wPass * 2.0

ord, Wn = scipy.signal.buttord(wPass*dt*2., wStop*dt*2., gPass, gStop)

#print "butterworth ord %f Wn %f c %f sc %f" % (ord, Wn, cutoff, stopCutoff)

b,a = scipy.signal.butter(ord, Wn, btype=btype)

return applyFilter(data, b, a, bidir=bidir)

开发者ID:SrikanthVelpuri,项目名称:tf-pose,代码行数:23,

示例18: filter_elevation

​点赞 6

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def filter_elevation(r0):

#-- calculate percentiles for IQR and RDE

#-- IQR: first and third quartiles (25th and 75th percentiles)

#-- RDE: 16th and 84th percentiles

#-- median: 50th percentile

Q1,Q3,P16,P84,MEDIAN = np.percentile(r0,[25,75,16,84,50])

#-- calculate interquartile range

IQR = Q3 - Q1

#-- calculate robust dispersion estimator (RDE)

RDE = P84 - P16

#-- IQR pass: residual-(median value) is within 75% of IQR

#-- RDE pass: residual-(median value) is within 50% of P84-P16

return (0.75*IQR,0.5*RDE,MEDIAN)

#-- PURPOSE: try fitting a surface to the signal photons with progressively

#-- less confidence if no valid surface is found

开发者ID:tsutterley,项目名称:read-ICESat-2,代码行数:18,

示例19: find_clock_frequency

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def find_clock_frequency(spectrum):

maxima = scipy.signal.argrelextrema(spectrum, numpy.greater_equal)[0]

while maxima[0] < 2:

maxima = maxima[1:]

if maxima.any():

threshold = max(spectrum[2:-1])*0.8

indices_above_threshold = numpy.argwhere(spectrum[maxima] > threshold)

return maxima[indices_above_threshold[0]]

else:

return 0

开发者ID:mossmann,项目名称:clock-recovery,代码行数:12,

示例20: find_clock_frequency

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def find_clock_frequency(spectrum):

maxima = scipy.signal.argrelextrema(spectrum, numpy.greater_equal)[0]

while maxima[0] < 3:

maxima = maxima[1:]

if maxima.any():

threshold = max(spectrum[5:-4])*0.8

indices_above_threshold = numpy.argwhere(spectrum[maxima] > threshold)

return maxima[indices_above_threshold[0][0]]

else:

return 0

# input: complex valued samples

# output: signed FFT bin number of detected frequency

开发者ID:mossmann,项目名称:clock-recovery,代码行数:15,

示例21: correct_frequency_offset

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def correct_frequency_offset(samples, offset):

a = array(samples)

original_fft = scipy.fft(a)

if offset < 0:

offset = len(a) + offset

shifted_fft = append(original_fft[offset:], original_fft[:offset])

return scipy.ifft(shifted_fft, len(a))

# input: complex valued samples

# input signal must be centered at 0 frequency

# output: FFT bin number of chip rate

开发者ID:mossmann,项目名称:clock-recovery,代码行数:13,

示例22: detect_chip_rate

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def detect_chip_rate(samples):

a = array(samples)

return find_clock_frequency(abs(scipy.fft(a*a)))

# input: complex valued samples

# input signal must be centered at 0 frequency

# output: subset of samples with optimal sampling time for each chip

开发者ID:mossmann,项目名称:clock-recovery,代码行数:9,

示例23: test_window_types

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_window_types(signal, framelength, window):

"""

Test if callable and fixed value windows work

"""

stft.spectrogram(signal, framelength=framelength, window=window)

开发者ID:nils-werner,项目名称:stft,代码行数:8,

示例24: test_precision

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_precision(channels, padding, signal, framelength, halved):

"""

Test if transform-inverse identity holds

"""

a = signal

x = stft.spectrogram(

a, framelength=framelength, padding=padding, halved=halved

)

y = stft.ispectrogram(x)

assert numpy.allclose(a, y)

开发者ID:nils-werner,项目名称:stft,代码行数:15,

示例25: test_multiple_transforms

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_multiple_transforms(signal):

"""

Test if giving multiple different transforms works OK

"""

a = signal

x = stft.spectrogram(a, transform=[scipy.fft.fft, numpy.fft.fft])

y = stft.ispectrogram(x, transform=[scipy.fft.ifft, numpy.fft.ifft])

assert numpy.allclose(a, y)

开发者ID:nils-werner,项目名称:stft,代码行数:13,

示例26: test_rms

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_rms(channels, padding, signal, framelength, halved):

"""

Test if transform-inverse identity holds

"""

a = signal

x = stft.spectrogram(

a, framelength=framelength, padding=padding, halved=halved

)

y = stft.ispectrogram(x)

assert numpy.sqrt(numpy.mean((a - y) ** 2)) < 1e-8

开发者ID:nils-werner,项目名称:stft,代码行数:15,

示例27: test_maxdim

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_maxdim():

"""

Test if breaking elementary limitations (2D signal, 3D spectrogram at most)

are caught appropriately

"""

a = numpy.random.random((512, 2, 2))

with pytest.raises(ValueError):

stft.spectrogram(a)

b = numpy.random.random((512, 2, 2, 3))

with pytest.raises(ValueError):

# we cannot infer data from a NumPy array, so we set framelengt here

stft.ispectrogram(b, framelength=1024)

开发者ID:nils-werner,项目名称:stft,代码行数:17,

示例28: test_issue1

​点赞 5

# 需要导入模块: import scipy [as 别名]

# 或者: from scipy import signal [as 别名]

def test_issue1():

"""

Passing a (x, 1) shape signal created a 3D tensor output, while

a (x,) shape signal created a 2D matrix. This should not happen.

"""

a = numpy.random.random((512, 1))

b = stft.spectrogram(a)

assert b.ndim == 2

开发者ID:nils-werner,项目名称:stft,代码行数:13,

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值