本文整理汇总了Python中scipy.signal.shape方法的典型用法代码示例。如果您正苦于以下问题:Python signal.shape方法的具体用法?Python signal.shape怎么用?Python signal.shape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.signal
的用法示例。
在下文中一共展示了signal.shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: frame_signal
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def frame_signal(self, signal, window):
frames = []
for beg_i in range(0, signal.shape[0], self.hop):
frame = signal[beg_i:beg_i + self.win]
if len(frame) < self.win:
# pad right size with zeros
P = self.win - len(frame)
frame = np.concatenate((frame,
np.zeros(P,)), axis=0)
frame = frame * window
frames.append(frame[None, :])
frames = np.concatenate(frames, axis=0)
return frames
# @profile
示例2: __call__
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def __call__(self, pkg, cached_file=None):
pkg = format_package(pkg)
wav = pkg['chunk']
y = wav.data.numpy()
max_frames = y.shape[0] // self.hop
if cached_file is not None:
# load pre-computed data
mfcc = torch.load(cached_file)
beg_i = pkg['chunk_beg_i'] // self.hop
end_i = pkg['chunk_end_i'] // self.hop
mfcc = mfcc[:, beg_i:end_i]
pkg[self.name] = mfcc
else:
# print(y.dtype)
mfccs = self.__execute_command__(y, self.cmd)
assert mfccs is not None, (
"Mfccs extraction failed"
)
pkg[self.name] = torch.tensor(mfccs[:,:max_frames].astype(np.float32))
# Overwrite resolution to hop length
pkg['dec_resolution'] = self.hop
return pkg
示例3: adjust_signals
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def adjust_signals(self, signal):
"""
Add simple heuristics (based on examining learnt policy actions distribution):
- repeat same buy or sell signal `kernel_size - 1` times.
"""
i = 0
while i < signal.shape[0]:
j = 1
if signal[i] != 0:
# if got buy, sell or close - repeat several times
while i + j < signal.shape[0] and j < self.kernel_size - 1:
signal[i + j] = signal[i]
j += 1
i = i + j
return signal
示例4: fit_sphere
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def fit_sphere(z):
"""Fit a sphere to data.
Parameters
----------
z : `numpy.ndarray`
2D array of data
Returns
-------
`numpy.ndarray`
sphere data
"""
x, y = e.linspace(-1, 1, z.shape[1]), e.linspace(-1, 1, z.shape[0])
xx, yy = e.meshgrid(x, y)
pts = e.isfinite(z)
xx_, yy_ = xx[pts].flatten(), yy[pts].flatten()
rho, phi = cart_to_polar(xx_, yy_)
focus = defocus(rho, phi)
coefs = e.linalg.lstsq(e.stack([focus, e.ones(focus.shape)]).T, z[pts].flatten(), rcond=None)[0]
rho, phi = cart_to_polar(xx, yy)
sphere = defocus(rho, phi) * coefs[0]
return sphere
示例5: real_spectrum
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def real_spectrum(signal, axis=-1, **kwargs):
try:
import matplotlib.pyplot as plt
except ImportError:
import warnings
warnings.warn("Matplotlib is required for plotting")
return
S = np.fft.rfft(signal, axis=axis)
f = np.arange(S.shape[axis]) / float(2 * S.shape[axis])
plt.subplot(2, 1, 1)
P = dB(S)
plt.plot(f, P, **kwargs)
plt.subplot(2, 1, 2)
phi = np.unwrap(np.angle(S))
plt.plot(f, phi, **kwargs)
示例6: resample
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def resample(signal, sc, clip = True, num_samples = None):
#print 'Called', clip
#ut.tic()
if USE_SCIKITS_SAMPLERATE:
r = np.array(scikits.samplerate.resample(signal, sc, 'sinc_best'), 'd')
assert not np.any(np.isinf(r)) and not np.any(np.isnan(r))
else:
#print signal.shape[0], int(round(signal.shape[0] * sc))
n = int(round(signal.shape[0] * sc)) if num_samples is None else num_samples
#print 'converting:', signal.shape[0], '->', n
r = scipy.signal.resample(signal, n)
if clip:
r = np.clip(r, -1, 1)
#ut.toc()
return r
示例7: cut_signal
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def cut_signal(signal, new_sr, old_sr):
new_signal = signal[: good_resample_length(signal.shape[0], new_sr, old_sr)]
#print signal.shape[0], new_signal.shape[0]
return new_signal
#r = max(1, np.floor(old_sr / new_sr)) * (new_sr / 100)
# r = 100
# return signal[:int(np.floor(signal.shape[0] / r) * r)]
# original
# def good_resample_length(n, new_sr, old_sr, factor = 100):
# assert new_sr % factor == 0 and old_sr % factor == 0
# return int(np.floor(n / factor) * factor)
# def good_resample_length(n, new_sr, old_sr, factor = 100):
# factor = new_sr / float(old_sr)
# new_len = int(np.floor(n / factor) * factor)
# print 'New length:', new_len, 'Factor:', factor
# return new_len
示例8: addnoise_asl
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def addnoise_asl(self, clean, noise, srate, nbits, snr, do_IRS=False):
if do_IRS:
# Apply IRS filter simulating telephone
# handset BW [300, 3200] Hz
clean = self.apply_IRS(clean, srate, nbits)
Px, asl, c0 = self.asl_P56(clean, srate, nbits)
# Px is active speech level ms energy
# asl is active factor
# c0 is active speech level threshold
x = clean
x_len = x.shape[0]
noise_len = noise.shape[0]
if noise_len <= x_len:
print('Noise length: ', noise_len)
print('Speech length: ', x_len)
raise ValueError('Noise length has to be greater than speech '
'length!')
rand_start_limit = int(noise_len - x_len + 1)
rand_start = int(np.round((rand_start_limit - 1) * np.random.rand(1) \
+ 1))
noise_segment = noise[rand_start:rand_start + x_len]
noise_bounds = (rand_start, rand_start + x_len)
if do_IRS:
noise_segment = self.apply_IRS(noise_segment, srate, nbits)
Pn = np.dot(noise_segment.T, noise_segment) / x_len
# we need to scale the noise segment samples to obtain the
# desired SNR = 10 * log10( Px / ((sf ** 2) * Pn))
sf = np.sqrt(Px / Pn / (10 ** (snr / 10)))
noise_segment = noise_segment * sf
noisy = x + noise_segment
return noisy, noise_bounds
示例9: estimate_actions
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def estimate_actions(self, episode_data):
"""
Estimates hold/buy/sell signals based on local peaks filtered by time horizon and signal amplitude.
Args:
episode_data: 1D np.array of unscaled [but possibly resampled] price values in OHL[CV] format
Returns:
1D vector of signals of same length as episode_data
"""
# Find local maxima and minima indices within time horizon:
max_ind = signal.argrelmax(episode_data, order=self.time_threshold)
min_ind = signal.argrelmin(episode_data, order=self.time_threshold)
indices = np.append(max_ind, min_ind)
# Append first and last points:
indices = np.append(indices, [0, episode_data.shape[0] - 1])
indices = np.sort(indices)
indices_and_values = []
for i in indices:
indices_and_values.append([episode_data[i], i])
# Filter by value:
indices_and_values = self.filter_by_margine(indices_and_values, self.value_threshold)
#print('filtered_indices_and_values:', indices_and_values)
# Estimate advised actions (no 'close' btw):
# Assume all 'hold':
advice = np.ones(episode_data.shape[0], dtype=np.uint32) * self.action_space[0]
for num, (v, i) in enumerate(indices_and_values[:-1]):
if v < indices_and_values[num + 1][0]:
advice[i] = self.action_space[1]
else:
advice[i] = self.action_space[2]
return advice
示例10: fit
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def fit(self, episode_data, resampling_factor=1):
"""
Estimates `advised` actions probabilities distribution based on data received.
Args:
episode_data: 1D np.array of unscaled price values in OHL[CV] format
resampling_factor: factor by which to resample given data
by taking min/max values inside every resampled bar
Returns:
Np.array of size [resampled_data_size, actions_space_size] of probabilities of advised actions, where
resampled_data_size = int(len(episode_data) / resampling_factor) + 1/0
"""
# Vector of advised actions:
data = self.resample_data(episode_data, resampling_factor)
signals = self.estimate_actions(data)
signals = self.adjust_signals(signals)
# One-hot actions encoding:
actions_one_hot = np.zeros([signals.shape[0], len(self.action_space)])
actions_one_hot[np.arange(signals.shape[0]), signals] = 1
# Want a bit relaxed discrete distribution over actions instead of one hot (heuristic):
actions_distr = np.zeros(actions_one_hot.shape)
# For all actions except 'hold' (due to heuristic skewness):
actions_distr[:, 0] = actions_one_hot[:, 0]
# ...spread out actions probabilities by convolving with gaussian kernel :
for channel in range(1, actions_one_hot.shape[-1]):
actions_distr[:, channel] = np.convolve(actions_one_hot[:, channel], self.kernel, mode='same') + 0.1
# Normalize:
actions_distr /= actions_distr.sum(axis=-1)[..., None]
return actions_distr
示例11: resample_data
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def resample_data(self, episode_data, factor=1):
"""
Resamples raw observations according to given skip_frame value
and estimates mean value of newly formed bars.
Args:
episode_data: np.array of shape [episode_length, values]
factor: scalar
Returns:
np.array of median Hi/Lo observations of size [int(episode_length/skip_frame) + 1, 1]
"""
# Define resampled size and [possibly] extend
# to complete last bar by padding with values from very last column:
resampled_size = int(episode_data.shape[0] / factor)
#print('episode_data.shape:', episode_data.shape)
if episode_data.shape[0] / factor > resampled_size:
resampled_size += 1
pad_size = resampled_size * factor - episode_data.shape[0]
#print('pad_size:', pad_size)
episode_data = np.append(
episode_data,
np.zeros([pad_size, episode_data.shape[-1]]) + episode_data[-1, :][None,:],
axis=0
)
#print('new_episode_data.shape:', episode_data.shape)
# Define HI and Low inside every new bar:
v_high = np.reshape(episode_data[:,1], [resampled_size, -1]).max(axis=-1)
v_low = np.reshape(episode_data[:, 2], [resampled_size, -1]).min(axis=-1)
# ...and yse Hi/Low mean along time_embedding:
data = np.stack([v_high, v_low], axis=-1).mean(axis=-1)
return data
示例12: fit_plane
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def fit_plane(x, y, z):
"""Fit a plane to data.
Parameters
----------
x : `numpy.ndarray`
1D array of x (axis 1) values
y : `numpy.ndarray`
1D array of y (axis 0) values
z : `numpy.ndarray`
2D array of z values
Returns
-------
`numpy.ndarray`
array representation of plane
"""
pts = e.isfinite(z)
if len(z.shape) > 1:
x, y = e.meshgrid(x, y)
xx, yy = x[pts].flatten(), y[pts].flatten()
else:
xx, yy = x, y
flat = e.ones(xx.shape)
coefs = e.linalg.lstsq(e.stack([xx, yy, flat]).T, z[pts].flatten(), rcond=None)[0]
plane_fit = coefs[0] * x + coefs[1] * y + coefs[2]
return plane_fit
示例13: psd
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def psd(height, sample_spacing, window=None):
"""Compute the power spectral density of a signal.
Parameters
----------
height : `numpy.ndarray`
height or phase data
sample_spacing : `float`
spacing of samples in the input data
window : {'welch', 'hann'} or ndarray, optional
Returns
-------
x : `numpy.ndarray`
ordinate x frequency axis
y : `numpy.ndarray`
ordinate y frequency axis
psd : `numpy.ndarray`
power spectral density
Notes
-----
See GH_FFT for a rigorous treatment of FFT scalings
https://holometer.fnal.gov/GH_FFT.pdf
"""
window = make_window(height, sample_spacing, window)
fft = e.fft.ifftshift(e.fft.fft2(e.fft.fftshift(height * window)))
psd = abs(fft)**2 # mag squared first as per GH_FFT
fs = 1 / sample_spacing
S2 = (window**2).sum()
coef = S2 * fs * fs
psd /= coef
ux = forward_ft_unit(sample_spacing, height.shape[1])
uy = forward_ft_unit(sample_spacing, height.shape[0])
return ux, uy, psd
示例14: synthesize_surface_from_psd
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def synthesize_surface_from_psd(psd, nu_x, nu_y):
"""Synthesize a surface height map from PSD data.
Parameters
----------
psd : `numpy.ndarray`
PSD data, units nm²/(cy/mm)²
nu_x : `numpy.ndarray`
x spatial frequency, cy/mm
nu_y : `numpy.ndarray`
y spatial frequency, cy_mm
"""
# generate a random phase to be matched to the PSD
randnums = e.random.rand(*psd.shape)
randfft = e.fft.fft2(randnums)
phase = e.angle(randfft)
# calculate the output window
# the 0th element of nu_y has the greatest frequency in magnitude because of
# the convention to put the nyquist sample at -fs instead of +fs for even-size arrays
fs = -2 * nu_y[0]
dx = dy = 1 / fs
ny, nx = psd.shape
x, y = e.arange(nx) * dx, e.arange(ny) * dy
# calculate the area of the output window, "S2" in GH_FFT notation
A = x[-1] * y[-1]
# use ifft to compute the PSD
signal = e.exp(1j * phase) * e.sqrt(A * psd)
coef = 1 / dx / dy
out = e.fft.ifftshift(e.fft.ifft2(e.fft.fftshift(signal))) * coef
out = out.real
return x, y, out
示例15: pvr
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import shape [as 别名]
def pvr(self):
"""Peak-to-Valley residual.
Notes
-----
See:
C. Evans, "Robust Estimation of PV for Optical Surface Specification and Testing"
in Optical Fabrication and Testing, OSA Technical Digest (CD)
(Optical Society of America, 2008), paper OWA4.
http://www.opticsinfobase.org/abstract.cfm?URI=OFT-2008-OWA4
"""
coefs, residual = zernikefit(self.phase, terms=36, residual=True, map_='Fringe')
fz = FringeZernike(coefs, samples=self.shape[0])
return fz.pv + 3 * residual