def test_basic(self): assert_allclose(signal.triang(6, True), [1 / 6, 1 / 2, 5 / 6, 5 / 6, 1 / 2, 1 / 6]) assert_allclose(signal.triang(7), [1 / 4, 1 / 2, 3 / 4, 1, 3 / 4, 1 / 2, 1 / 4]) assert_allclose(signal.triang(6, sym=False), [1 / 4, 1 / 2, 3 / 4, 1, 3 / 4, 1 / 2])
def __init__(self, fibers, innervation_ratio, spindleCallback, golgiCallback): self.fibers = fibers self.fiber_strengths = np.array([f[0] for f in self.fibers]) self.fiber_count = len(self.fibers) self.innervation_ratio = innervation_ratio # Divide our fibers into motor units self.motor_unit_count = self.fiber_count / self.innervation_ratio self.extra_fiber_count = self.fiber_count % self.innervation_ratio self.activations = None # The set of innervation filters across all fibers self.innervation_filter = [] # For each motor unit for i in range(self.motor_unit_count - 1): # A triangle filter around the center of the unit # This will simulate the diminishing strength a signal has on fibers distant from # a motor neuron. f = triang(innervation_ratio) self.innervation_filter.extend(f) # Final motor unit picks up any extra fibers self.innervation_filter.extend(triang(self.innervation_ratio + self.extra_fiber_count)) self.innervation_filter = self.innervation_filter
def test_basic(self): assert_allclose(signal.triang(6, True), [1/6, 1/2, 5/6, 5/6, 1/2, 1/6]) assert_allclose(signal.triang(7), [1/4, 1/2, 3/4, 1, 3/4, 1/2, 1/4]) assert_allclose(signal.triang(6, sym=False), [1/4, 1/2, 3/4, 1, 3/4, 1/2])
def get_smoothing_filter( window_size=(9, 9), window_shape="gauss", plot_filter=False): """Computes and returns a smoothing filter. :param window_size: Filter window size, defaults to (9, 9) :type window_size: tuple(int, int), optional :param window_shape: Filter type, defaults to 'gauss' :type window_shape: str, optional. Options: {'gauss'} | 'tri' | 'circ' | 'rect'. :param plot_filter: Whether to plot the filter or not, defaults to False :type plot_filter: boolean, optional :raises ValueError: In case of wrong filter name :return: The filter :rtype: `numpy.array_like` """ window_size = np.array(window_size) if window_shape.lower() == "tri": window_filter = spsig.triang(window_size[0])[:, None] * spsig.triang( window_size[1])[None, :] elif window_shape.lower() == "circ": tt = np.linspace(-(window_size[0] - 1) / 2, (window_size[0] - 1) / 2, window_size[0]) ss = np.linspace(-(window_size[1] - 1) / 2, (window_size[1] - 1) / 2, window_size[1]) [tt, ss] = np.meshgrid(tt, ss, indexing="ij") window_filter = np.sqrt(tt**2 + ss**2) <= (window_size[1] - 1) / 2 elif window_shape.lower() == "gauss": tt = np.linspace(-(window_size[0] - 1) / 2, (window_size[0] - 1) / 2, window_size[0]) ss = np.linspace(-(window_size[1] - 1) / 2, (window_size[1] - 1) / 2, window_size[1]) [tt, ss] = np.meshgrid(tt, ss, indexing="ij") window_filter = np.exp(-((2 * tt)**2 / window_size[0] + (2 * ss)**2 / window_size[1])) elif window_shape.lower() == "rect": window_filter = np.ones(window_size) else: raise ValueError("Unknown filter: %s" % window_shape) if plot_filter: tt = np.linspace(-(window_size[0] - 1) / 2, (window_size[0] - 1) / 2, window_size[0]) ss = np.linspace(-(window_size[1] - 1) / 2, (window_size[1] - 1) / 2, window_size[1]) [tt, ss] = np.meshgrid(tt, ss, indexing="ij") f = plt.figure() ax = f.add_subplot(1, 1, 1, projection="3d") ax.plot_surface(tt, ss, window_filter) ax.view_init(12, -7.5) plt.show() return window_filter / np.sum(window_filter)
def melfilterbank(nfilters, nsamples, freq, lofreq, hifreq): """Create Mel filterbank. Parameters ---------- nfilters : int Number of Mel filters. nsamples : int Number of samples per filter. freq : int or float Frequency (sample rate) of the signal. lofreq : int or float Left boundary for fitlers. higreq : int or float Right boundary for fitlers. Returns ------- bank : ndarray 2D array (nfilters, nsamples) of Mel filters. """ lomel = hz2mel(lofreq) himel = hz2mel(hifreq) melpoints = np.linspace(lomel, himel, nfilters + 2) points = np.vectorize(mel2hz)(melpoints) bins = np.asarray(points * (nsamples / freq), dtype=int) bank = np.zeros([nfilters, nsamples]) for i in range(nfilters): start = bins[i] end = bins[i + 2] bank[i][start:end] = signal.triang(end - start) return bank
def filter_csd(self): '''Spatial filtering of the CSD estimate, using an N-point filter''' if not self.f_order > 0 and type(self.f_order) == type(3): raise Exception, 'Filter order must be int > 0!' if self.f_type == 'boxcar': num = ss.boxcar(self.f_order) denom = pl.array([num.sum()]) elif self.f_type == 'hamming': num = ss.hamming(self.f_order) denom = pl.array([num.sum()]) elif self.f_type == 'triangular': num = ss.triang(self.f_order) denom = pl.array([num.sum()]) elif self.f_type == 'gaussian': num = ss.gaussian(self.f_order[0], self.f_order[1]) denom = pl.array([num.sum()]) else: raise Exception, '%s Wrong filter type!' % self.f_type num_string = '[ ' for i in num: num_string = num_string + '%.3f ' % i num_string = num_string + ']' denom_string = '[ ' for i in denom: denom_string = denom_string + '%.3f ' % i denom_string = denom_string + ']' print 'discrete filter coefficients: \nb = %s, \na = %s' % \ (num_string, denom_string) self.csd_filtered = pl.empty(self.csd.shape) for i in xrange(self.csd.shape[1]): self.csd_filtered[:, i] = ss.filtfilt(num, denom, self.csd[:, i])
def sineModelSynth(tfreq, tmag, tphase, N, H, fs): """ Synthesis of a sound using the sinusoidal model tfreq,tmag,tphase: frequencies, magnitudes and phases of sinusoids N: synthesis FFT size, H: hop size, fs: sampling rate returns y: output array sound """ hN = N//2 # half of FFT size for synthesis L = tfreq.shape[0] # number of frames pout = 0 # initialize output sound pointer ysize = H*(L+3) # output sound size y = np.zeros(ysize) # initialize output array sw = np.zeros(N) # initialize synthesis window ow = triang(2*H) # triangular window sw[hN-H:hN+H] = ow # add triangular window bh = blackmanharris(N) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hN-H:hN+H] = sw[hN-H:hN+H]/bh[hN-H:hN+H] # normalized synthesis window lastytfreq = tfreq[0,:] # initialize synthesis frequencies ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size) # initialize synthesis phases for l in range(L): # iterate over all frames if (tphase.size > 0): # if no phases generate them ytphase = tphase[l,:] else: ytphase += (np.pi*(lastytfreq+tfreq[l,:])/fs)*H # propagate phases Y = UF.genSpecSines(tfreq[l,:], tmag[l,:], ytphase, N, fs) # generate sines in the spectrum lastytfreq = tfreq[l,:] # save frequency for phase propagation ytphase = ytphase % (2*np.pi) # make phase inside 2*pi yw = np.real(fftshift(ifft(Y))) # compute inverse FFT y[pout:pout+N] += sw*yw # overlap-add and apply a synthesis window pout += H # advance sound pointer y = np.delete(y, range(hN)) # delete half of first window y = np.delete(y, range(y.size-hN, y.size)) # delete half of the last window return y
def square_wave_gen(number_half_waves, resolution, samples_per_wave): """ Takes in number of half waves and resolution in multiples of 12 samples per wave 1 = 12 samples per wave 2 = 24 so on Output square wave oscillating at 40,000 Hz with the x axis in microseconds and centered around zero """ from scipy import signal import matplotlib.pyplot as plt import numpy as np number_half_waves += 10 # One wave is 25 microseconds t = np.linspace(0, 12.5 * number_half_waves, int(samples_per_wave * resolution * (number_half_waves / 2)), endpoint=False) #wave = -signal.square(2 * np.pi * 0.04 * t)*1.65 Fs = 40000 * 12.5 * 2 ## Sampling Rate f = 40000 ## Frequency (in Hz) ####### sine wave ########### wave = -np.sin(2 * np.pi * f * t / Fs) triangle = signal.triang(len(t)) peaked_wave = np.multiply(triangle, wave) return t, wave
def sineSubtraction(x, N, H, sfreq, smag, sphase, fs): """ Subtract sinusoids from a sound x: input sound, N: fft-size, H: hop-size sfreq, smag, sphase: sinusoidal frequencies, magnitudes and phases returns xr: residual sound """ hN = N/2 # half of fft size x = np.append(np.zeros(hN),x) # add zeros at beginning to center first window at sample 0 x = np.append(x,np.zeros(hN)) # add zeros at the end to analyze last sample bh = blackmanharris(N) # blackman harris window w = bh/ sum(bh) # normalize window sw = np.zeros(N) # initialize synthesis window sw[hN-H:hN+H] = triang(2*H) / w[hN-H:hN+H] # synthesis window L = sfreq.shape[0] # number of frames, this works if no sines xr = np.zeros(x.size) # initialize output array pin = 0 for l in range(L): xw = x[pin:pin+N]*w # window the input sound X = fft(fftshift(xw)) # compute FFT Yh = UF_C.genSpecSines(N*sfreq[l,:]/fs, smag[l,:], sphase[l,:], N) # generate spec sines Xr = X-Yh # subtract sines from original spectrum xrw = np.real(fftshift(ifft(Xr))) # inverse FFT xr[pin:pin+N] += xrw*sw # overlap-add pin += H # advance sound pointer xr = np.delete(xr, range(hN)) # delete half of first window which was added in stftAnal xr = np.delete(xr, range(xr.size-hN, xr.size)) # delete half of last window which was added in stftAnal return xr
def triangle_periodic(img_width, period, offset, bw): '''Spatial forcing function - Periodic Triangle with bandwidth (bw) Parameters ---------- img_width : array_like Width of image singal period: int Period in pixels of forcing function offset: int Offset in pixels (i.e. cyclic shift) bw : float Bandwidth (width in pixel from base of triangle) of forcing function Returns ------- g(x) : complex Desired spatial response of uniform phantom with periodic off resonance ''' bw = round(bw) period = round(period) assert period >= bw window = triang(bw) window = np.concatenate((window, np.zeros(period - bw))) num_of_windows = math.ceil(img_width / period) response = np.tile(window, (num_of_windows)) response = response[:img_width] response = np.roll(response, offset) return response
def sineModelSynth(tfreq, tmag, tphase, N, H, fs): """ Synthesis of a sound using the sinusoidal model tfreq, tmag, tphase: frequencies, magnitudes and phases of sinusoids N: synthesis FFT size, H: hop size, fs: sampling rate returns y: output array sound """ hN = N / 2 # half of FFT size for synthesis L = tfreq.shape[0] # number of frames pout = 0 ysize = H * (L+3) y = np.zeros(ysize) # synthesis window sw = np.zeros(N) ow = triang(2 * H) sw[hN-H:hN+H] = ow bh = blackmanharris(N) bh = bh / sum(bh) sw[hN-H:hN+H] = sw[hN-H:hN+H] / bh[hN-H:hN+H] lastytfreq = tfreq[0,:] ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size) for l in range(L): # iterate over all frames if (tphase.size > 0): ytphase = tphase[l, :]
def sineModelSynth(tfreq, tmag, tphase, N, H, fs): """ Synthesis of a sound using the sinusoidal model tfreq,tmag,tphase: frequencies, magnitudes and phases of sinusoids N: synthesis FFT size, H: hop size, fs: sampling rate returns y: output array sound """ hN = N/2 # half of FFT size for synthesis L = tfreq.shape[0] # number of frames pout = 0 # initialize output sound pointer ysize = H*(L+3) # output sound size y = np.zeros(ysize) # initialize output array sw = np.zeros(N) # initialize synthesis window ow = triang(2*H) # triangular window sw[hN-H:hN+H] = ow # add triangular window bh = blackmanharris(N) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hN-H:hN+H] = sw[hN-H:hN+H]/bh[hN-H:hN+H] # normalized synthesis window lastytfreq = tfreq[0,:] # initialize synthesis frequencies ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size) # initialize synthesis phases for l in range(L): # iterate over all frames if (tphase.size > 0): # if no phases generate them ytphase = tphase[l,:] else: ytphase += (np.pi*(lastytfreq+tfreq[l,:])/fs)*H # propagate phases Y = UF.genSpecSines(tfreq[l,:], tmag[l,:], ytphase, N, fs) # generate sines in the spectrum lastytfreq = tfreq[l,:] # save frequency for phase propagation ytphase = ytphase % (2*np.pi) # make phase inside 2*pi yw = np.real(fftshift(ifft(Y))) # compute inverse FFT y[pout:pout+N] += sw*yw # overlap-add and apply a synthesis window pout += H # advance sound pointer y = np.delete(y, range(hN)) # delete half of first window y = np.delete(y, range(y.size-hN, y.size)) # delete half of the last window return y
def sineModelSynth(tfreq, tmag, tphase, M, H, fs): """ Synthesis of a sound using the sinusoidal model *** The hop size needs to be the same as what was used for the sineModelAnal *** *** (This probably means that the window/FFT size should be about the same as well) *** tfreq,tmag,tphase: frequencies, magnitudes (in dB) and phases of sinusoids tfreq should be within the range of frequencies captured by an FFT of size M and sampling rate fs M: synthesis FFT size (Blackman-Harris window size - should be a power of two for iFFT) H: hop size, fs: sampling rate returns y: output array sound """ if not isPower2(M): M_new = nextbiggestpower2(M) warnings.warn( "Non-power of 2 FFT size of {} passed to sineModelSynth, using {} instead" .format(M, M_new)) M = M_new hM = M // 2 # half analysis window size L = tfreq.shape[0] # number of frames pout = 0 # initialize output sound pointer ysize = H * ( L - 1 ) + M + 1 # output sound size: H*(L-1) is the number of samples in signal, NB added 1 print('ysize, M', ysize, M) # plus the length of the window y = np.zeros(ysize) # initialize output array sw = np.zeros(M) # initialize synthesis window ow = triang(hM) # triangular window - half of Blackman-Harris window size htriM = hM // 2 # half analysis window size sw[hM - htriM:hM + htriM] = ow # add triangular window to the middle of sw bh = blackmanharris(M) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hM - htriM:hM + htriM] = sw[hM - htriM:hM + htriM] / bh[hM - htriM:hM + htriM] # normalized synthesis window lastytfreq = tfreq[0, :] # initialize synthesis frequencies ytphase = 2 * np.pi * np.random.rand( tfreq[0, :].size) # initialize synthesis phases for l in range(L): # iterate over all frames if (tphase.size > 0): ytphase = tphase[l, :] else: # if no phases generate them ytphase += (np.pi * (lastytfreq + tfreq[l, :]) / fs) * H # propagate phases Y = UF.genSpecSines_p(tfreq[l, :], tmag[l, :], ytphase, M, fs) # generate sines in the spectrum lastytfreq = tfreq[l, :] # save frequency for phase propagation ytphase = ytphase % (2 * np.pi) # make phase inside 2*pi yw = np.real(fftshift(ifft(Y))) # compute inverse FFT y[pout:pout + M] += sw * yw # overlap-add and apply a synthesis window pout += H # advance sound pointer y = np.delete(y, range(hM)) # delete half of first window y = np.delete(y, range(y.size - hM, y.size)) # delete half of the last window return y
def win_sel(win_str, win_size): """ Function returns a window vector based on window name. Note class can only use windows found in scipy.signal library. """ overlap = 0 if (win_str == 'blackmanharris'): win = sig.blackmanharris(win_size) overlap = .75 elif (win_str == 'blackman'): win = sig.blackman(win_size) elif (win_str == 'bartlett'): win = sig.bartlett(win_size) elif (win_str == 'hamming'): win = sig.hamming(win_size) elif (win_str == 'hanning'): win = sig.hanning(win_size) elif (win_str == 'hann'): win = sig.hann(win_size) elif (win_str == 'barthann'): win = sig.barthann(win_size) elif (win_str == 'triang'): win = sig.triang(win_size) elif (win_str == 'rect' or win_str == None): win = np.ones(win_size) else: print('Invalid Window Defined') return -1 return win, overlap
def choose_windows(type, wlen): """ type 1、 汉明窗 2、 海宁窗 3、 矩形窗 4、 三角窗 :param type: :param wlen: :return: """ if type == 1: window = np.array([ 0.54 - 0.46 * np.cos(2 * np.pi * n / (wlen - 1)) for n in range(wlen) ]) elif type == 2: window = np.array([ 0.5 * (1 - np.cos(2 * np.pi * n / (wlen - 1))) for n in range(wlen) ]) elif type == 3: window = np.ones(wlen) elif type == 4: window = signal.triang(wlen) return window
def sinewaveSynth(freq, mag, N, H, fs): # Synthesis of a time-varying sinusoid # freq,mag, phase: frequency, magnitude and phase of sinusoid, # N: synthesis FFT size, H: hop size, fs: sampling rate # returns y: output array sound hN = N/2 # half of FFT size for synthesis L = freq.size # number of frames pout = 0 # initialize output sound pointer ysize = H*(L+3) # output sound size y = np.zeros(ysize) # initialize output array sw = np.zeros(N) # initialize synthesis window ow = triang(2*H); # triangular window sw[hN-H:hN+H] = ow # add triangular window bh = blackmanharris(N) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hN-H:hN+H] = sw[hN-H:hN+H]/bh[hN-H:hN+H] # normalized synthesis window lastfreq = freq[0] # initialize synthesis frequencies phase = 0 # initialize synthesis phases for l in range(L): # iterate over all frames phase += (np.pi*(lastfreq+freq[l])/fs)*H # propagate phases Y = UF.genSpecSines(freq[l], mag[l], phase, N, fs) # generate sines in the spectrum lastfreq = freq[l] # save frequency for phase propagation yw = np.real(fftshift(ifft(Y))) # compute inverse FFT y[pout:pout+N] += sw*yw # overlap-add and apply a synthesis window pout += H # advance sound pointer y = np.delete(y, range(hN)) # delete half of first window y = np.delete(y, range(y.size-hN, y.size)) # delete half of the last window return y
def convolute(t_list, y_list, normal): """ """ convoluted = [] cx = [] for j in range(1, 200): line = signal.triang(j * 10) conv = signal.convolve(normal, line, 'same') / sum(line) v_list = velocity_transformation(t_list, 4) unnormal = [] for idx in range(len(conv)): unnormal.append(conv[idx] * t_list[idx]) convoluted.append(solve(v_list, unnormal)) cx.append(t_list[len(t_list) - j * 10] / 2) # if j == 50: # plotter(v_list, unnormal, "Velocity (m/s)", "Capture Flux", "Capture Flux vs Velocity after Convolution") c1 = [] for num in convoluted: c1.append((num - 1) * 886.3) min = .1 for idx in range(len(c1)): if abs(c1[idx] - (c1[0] + .1)) < min: min = abs(c1[idx] - (c1[0] + .1)) tenth_x = cx[idx] tenth_y = c1[idx] xlabel = 'Width of Triangle Signal (s)' ylabel = 'Correction in Seconds' title = 'Correction Dependence on Convolution to Triangle Signal' print('Width of Triangle Signal to get a tenth of a second error', tenth_x, 's')
def linearErodeInner(x, blend_size=10): """ Linear ramp erosion of an array. This function thresholds an array to values greater than zero, then erodes all edges to within the support of the thresholded array. If the array is not binary, it is reduced to a binary form, normalized from 0-1. Parameters ---------- x: array-like The array we wish to erode blend_size: int The amount of erosion we wish to perform. This number corresponds to the maximum distance inside the edge of the support of x. Returns ------- array-like: The eroded version of x. """ # Get dtype and backend dtype = getDatatype(x) backend = getBackend(x) # Normalize x _x = dcopy(x) _x[:] -= min(x) _x[:] = asarray(_x > 0, dtype, backend) # Create triangular wave s = sig.triang(2 * blend_size + 1) triang_2d = s[:, np.newaxis] * s triang_2d /= sum(triang_2d) triang_2d = asarray(triang_2d, dtype, backend) # Generate crop operator which pads edges for convolutionx padded_size = [scipy.fftpack.next_fast_len(int(s + 2 * blend_size)) for s in shape(_x)] x_padded = pad(_x, padded_size, pad_value='edge', center=True) # Pad triangular wave as well triang_2d_padded = pad(triang_2d, padded_size, center=True, pad_value=0) coords = argmax(triang_2d_padded) triang_2d_padded = zeros_like(triang_2d_padded) triang_2d_padded[coords] = 1.0 # Perform FFT convolution x_filtered = iFt(Ft(triang_2d_padded) * Ft(x_padded)) # x_filtered = sig.fftconvolve(np.asarray(triang_2d_padded), np.asarray(x_padded), mode='same') x_filtered = crop(x_filtered, shape(x), center=True) # # Threshold to within existing range x_filtered[:] -= 0.5 x_filtered[:] *= (real(x_filtered) >= 0) x_filtered[:] *= 2 # Return return x_filtered
def f(): window_type = display['window_type'] window_size = int(display['size']) p = float(display['param']) window = np.zeros(window_size) if window_type == 'square': window = np.ones(window_size) elif window_type == 'exponential': window = np.exp(np.arange(window_size) * p) elif window_type == 'hanning': window = np.hanning(window_size) elif window_type == 'blackman': window = np.blackman(window_size) elif window_type == 'ricker': window = ricker(window_size, p) elif window_type == 'gaussian': window = gaussian(window_size, p) elif window_type == 'barthann': window = barthann(window_size) elif window_type == 'flattop': window = flattop(window_size) elif window_type == 'cosine': window = cosine(window_size) elif window_type == 'triangle': window = triang(window_size) return window
def raw_ctd_filter(df=None, window="triangle", win_size=24, parameters=None): """ Filter raw CTD data using one of three window types (boxcar, hanning, triangle). Parameters ---------- df : DataFrame Raw CTD data window : str, optional Type of filter window win_size : int, optional Length of window in number of samples parameters : list of str, optional List of DataFrame columns to be filtered Returns ------- filtered_df : DataFrame CTD data with filtered parameters """ filter_df = df.copy() if parameters is not None: for p in parameters: if window == "boxcar": win = sig.boxcar(win_size) elif window == "hanning": win = sig.hann(win_size) elif window == "triangle": win = sig.triang(win_size) filter_df[p] = sig.convolve(filter_df[p], win, mode="same") / np.sum(win) return filter_df
def cqtfft(X, fs=44100, lo=12, hi=None): """ q, p = cqtfft(X, fs) Returns the complex constant-Q transform vector of fft vector X with sampling rate FS. Like chroma, but unwrapped. Here, Q = 16.817. """ #Q = 16.817 Q = 8.1658 if X.ndim == 2: X = X[:, 0].squeeze() if hi is None: hi = int(hz2midi(fs / 2)) p = scipy.arange(lo, hi) q = scipy.zeros(hi - lo) for i, midi in enumerate(p): center = X.size * midi2hz(midi) / fs width = int(center / Q) center = int(center) w = ss.triang(2 * width + 1) q[i] = scipy.inner(w, X[center - width:center + width + 1]) return q, p
def sineModelSynth(tfreq, tmag, tphase, N, H, fs): hN = N//2 L = tfreq.shape[0] out = 0 ysize = H*(L+3) y = np.zeros(ysize) synthWin = np.zeros(N) triWin = triang(H*2) synthWin[hN-H:hN+H] = triWin bh = blackmanharris(N) bh = bh / sum(bh) synthWin[hN-H:hN+H] = synthWin[hN-H:hN+H]/bh[hN-H:hN+H] lastytfreq = tfreq[0,:] ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size) for l in range(L): if (tphase.size > 0): ytphase = tphase[l,:] else: ytphase += (np.pi*(lastytfreq+tfreq[l,:])/fs)*H # propagate phases Y = U.genSinesSpectrum(tfreq[l,:], tmag[l,:], ytphase, N, fs) lastytfreq = tfreq[l,:] # save frequency for phase propagation ytphase = ytphase % (2*np.pi) yw = np.real(fftshift(ifft(Y))) y[out:out+N] += synthWin*yw out += H y = np.delete(y, range(hN)) y = np.delete(y, range(y.size-hN, y.size)) return y
def harmonicModel(x, fs, w, N, t, nH, minf0, maxf0, f0et): """ Analysis/synthesis of a sound using the sinusoidal harmonic model x: input sound, fs: sampling rate, w: analysis window, N: FFT size (minimum 512), t: threshold in negative dB, nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, maxf0: maximim f0 frequency in Hz, f0et: error threshold in the f0 detection (ex: 5), returns y: output array sound """ hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor x = np.append(np.zeros(hM2),x) # add zeros at beginning to center first window at sample 0 x = np.append(x,np.zeros(hM1)) # add zeros at the end to analyze last sample Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # init sound pointer in middle of anal window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yh = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # window for overlap-add hfreqp = [] f0t = 0 f0stable = 0 while pin<pend: #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, N) # compute dft ploc = UF.peakDetection(mX, t) # detect peak locations iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values ipfreq = fs * iploc/N f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable) # find f0 if ((f0stable==0)&(f0t>0)) \ or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)): f0stable = f0t # consider a stable f0 if it is close to the previous one else: f0stable = 0 hfreq, hmag, hphase = harmonicDetection(ipfreq, ipmag, ipphase, f0t, nH, hfreqp, fs) # find harmonics hfreqp = hfreq #-----synthesis----- Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns, fs) # generate spec sines fftbuffer = np.real(ifft(Yh)) # inverse FFT yh[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yh[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yh # overlap-add pin += H # advance sound pointer y = np.delete(y, range(hM2)) # delete half of first window which was added in stftAnal y = np.delete(y, range(y.size-hM1, y.size)) # add zeros at the end to analyze last sample return y
def sprModel(x, fs, w, N, t): """ Analysis/synthesis of a sound using the sinusoidal plus residual model, one frame at a time x: input sound, fs: sampling rate, w: analysis window, N: FFT size (minimum 512), t: threshold in negative dB, returns y: output sound, ys: sinusoidal component, xr: residual component """ hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT ysw = np.zeros(Ns) # initialize output sound frame xrw = np.zeros(Ns) # initialize output sound frame ys = np.zeros(x.size) # initialize output array xr = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] while pin<pend: #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, N) # compute dft ploc = UF.peakDetection(mX, t) # find peaks iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values ipfreq = fs*iploc/float(N) # convert peak locations to Hertz ri = pin-hNs-1 # input sound pointer for residual analysis xw2 = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xw2[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xw2[:hNs] X2 = fft(fftbuffer) # compute FFT for residual analysis #-----synthesis----- Ys = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs) # generate spec of sinusoidal component Xr = X2-Ys; # get the residual complex spectrum fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Ys)) # inverse FFT of sinusoidal spectrum ysw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window ysw[hNs-1:] = fftbuffer[:hNs+1] fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Xr)) # inverse FFT of residual spectrum xrw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window xrw[hNs-1:] = fftbuffer[:hNs+1] ys[ri:ri+Ns] += sw*ysw # overlap-add for sines xr[ri:ri+Ns] += sw*xrw # overlap-add for residual pin += H # advance sound pointer y = ys+xr # sum of sinusoidal and residual components return y, ys, xr
def _get_weights(shape): shape = shape[1:] weights = 1 for idx_d in range(len(shape)): slicey = [np.newaxis]*len(shape) slicey[idx_d] = slice(None) size = shape[idx_d] weights = weights*triang(size)[tuple(slicey)] return weights[np.newaxis, ].astype(np.float32)
def generate_peak(self, multipath=False, delta_dopp=0, delta_tau=0, delta_phase=0, alpha_att=1, ref_features=False): x = np.linspace(self.dopp[0], self.dopp[1], self.discr_size_fd) y = np.linspace(self.tau[0], self.tau[1], self.scale_code) # Create empty matrix for peaks matrix = np.zeros((self.discr_size_fd, self.scale_code)) # Convert tau/ doppler deviation into pixel scale xk = int(x.mean() + delta_dopp / (x.max() - x.min()) * self.discr_size_fd) yk = int(y.mean() + delta_tau / (y.max() - y.min()) * self.scale_code) # Generate triangle/ sinc function func1 = self.sign_amp * signal.triang(self.scale_code) func2 = self.sign_amp * np.sinc((x + delta_dopp) * self.Tint) # Only 1 principal peak for i, point in enumerate(func2): matrix[i] = alpha_att * func1 * point # Superpose 2 peaks. Weight matrix of MP peak by the matrix of principal peak if multipath: if xk >= 0: matrix = matrix[:matrix.shape[0]- xk, :matrix.shape[1]-yk] else: matrix = matrix[abs(xk):, :matrix.shape[1]-yk] # Split matrices in I, Q channels I = matrix * self.sin_cos_matrix(multipath=multipath, delta_dopp=delta_dopp, delta_phase=delta_phase, xk=xk, yk=yk)[0] Q = -matrix * self.sin_cos_matrix(multipath=multipath, delta_dopp=delta_dopp, delta_phase=delta_phase, xk=xk, yk=yk)[1] # Add noise model mean = self.noise_model()[0] var = self.noise_model()[1] module = np.sqrt(I**2 + Q**2) I += np.random.normal(mean, var, size=matrix.shape) Q += np.random.normal(mean, var, size=matrix.shape) #if ref_features: # print('check no normalization for reference') # I_norm = I[...,None] # Q_norm = Q[...,None] #else: I_norm = (I - module.min()) / (module.max() - module.min()) Q_norm = (Q - module.min()) / (module.max() - module.min()) module = (module - module.min()) / (module.max() - module.min()) #I_norm = I #Q_norm = Q #print('CHECK SCALE') I_norm = I_norm[...,None] Q_norm = Q_norm[...,None] matrix = np.concatenate((I_norm, Q_norm), axis=2) return matrix, module, xk, yk
def _get_weights(shape): shape_in = shape shape = shape[1:] weights = 1 for idx_d in range(len(shape)): slicey = [np.newaxis] * len(shape) slicey[idx_d] = slice(None) size = shape[idx_d] weights = weights * triang(size)[tuple(slicey)] return np.broadcast_to(weights, shape_in).astype(np.float32)
def output_waveform(seconds): #Here we make a triangle wave peak_v = 5 wave_form_step_size = 101 triangle_wave = signal.triang(wave_form_step_size) period = 30 #seconds x = np.int(np.round(np.mod(seconds, period) / period * (wave_form_step_size-1))) voltage = triangle_wave[x] * peak_v return voltage
def __generate_peak__(self, multipath=False, delta_dopp=0, delta_tau=0, delta_phase=0, alpha_att=1, ref_features=False): x = np.linspace(self.dopp[0], self.dopp[1], self.discr_size_fd) y = np.linspace(self.tau[0], self.tau[1], self.scale_code) # Create empty matrix for peaks matrix_i = np.zeros((self.discr_size_fd, self.scale_code)) matrix_q = np.zeros((self.discr_size_fd, self.scale_code)) matrix_tr_i = np.zeros((self.discr_size_fd, self.scale_code // 2)) matrix_tr_q = np.zeros((self.discr_size_fd, self.scale_code // 2)) # Convert tau/ doppler deviation into pixel scale xk = int(x.mean() + delta_dopp / (x.max() - x.min()) * self.discr_size_fd) yk = int(y.mean() + delta_tau / (y.max() - y.min()) * self.scale_code) # adjust xk if xk <= - matrix_i.shape[0] // 2: xk = matrix_i.shape[0] - abs(xk) if xk >= matrix_i.shape[0] // 2: xk = -(matrix_i.shape[0] - abs(xk)) # Generate triangle function func1 = self.sign_amp * signal.triang(self.scale_code // 2) # Generate sinc*sin / sinc*cos functions for I, Q channels sin_cos_array = self.__sin_cos_matrix__(multipath=multipath, delta_dopp=delta_dopp, delta_phase=delta_phase, xk=xk, yk=yk) func2i = self.sign_amp * np.sinc(x * self.Tint * SINC_WIDTH_COEF) * sin_cos_array[0] func2q = self.sign_amp * np.sinc(x * self.Tint * SINC_WIDTH_COEF) * sin_cos_array[1] # Only 1 principal peak for i, (pointi, pointq) in enumerate(zip(func2i, func2q)): matrix_tr_i[i] = alpha_att * func1 * pointi matrix_tr_q[i] = alpha_att * func1 * pointq # sum matrix_tr and matrix of background according interval offset matrix_i[:, 5:(self.scale_code // 2 + 5)] = matrix_tr_i matrix_q[:, 5:(self.scale_code // 2 + 5)] = matrix_tr_q # Apply offset on dopp (xk) and code to mutlipath peak if multipath: if xk >= 0: matrix_i = matrix_i[:matrix_i.shape[0]-xk, :matrix_i.shape[1]-yk] matrix_q = matrix_q[:matrix_q.shape[0]-xk, :matrix_q.shape[1]-yk] else: matrix_i = matrix_i[abs(xk):, :matrix_i.shape[1]-yk] matrix_q = matrix_q[abs(xk):, :matrix_q.shape[1]-yk] I = matrix_i Q = matrix_q I = I[...,None] Q = Q[...,None] matrix = np.concatenate((I, Q), axis=2) return matrix, xk, yk
def sine_model_synthesis(t_freq, t_mag, t_phase, n, h, fs): ''' Synthesis of a sound using the sinusoidal model t_freq, t_mag, t_phase: frequencies, magnitudes and phases of sinusoids n: synthesis FFT size h: hop size fs: sampling rate returns y: output array sound ''' h_n = n / 2 # half of FFT for synth L = t_freq.shape[0] # no. frames p_out = 0 # init ouputput sound pointer y_size = h * (L + 3) # output size y = np.zeros(y_size) # init output array sw = np.zeros(n) # init synth window tw = triang(2 * h) # triangular window sw[h_n - h:h_n + h] = tw # add triang window bh = blackmanharris(n) # blackman-harris window # normalize windows bh = bh / sum(bh) sw[h_n - h:h_n + h] = sw[h_n - h:h_n + h] / bh[h_n - h:h_n + h] last_y_t_freq = t_freq[0, :] # init synth freqs... y_t_phase = 2 * np.pi * np.random.rand(t_freq[0, :].size) # ...and phases # For all frames for l in range(L): # if no phases, then generate if (t_phase.size > 0): y_t_phase = t_phase[l, :] else: y_t_phase += (np.pi * (last_y_t_freq + t_freq[l, :]) / fs) * h # generate sines in spectrum Y = uf.genSpecSines(t_freq[l, :], t_mag[l, :], y_t_phase, n, fs) # save freq for phase propagation last_y_freq = t_freq[l, :] # bound freq inside 2pi y_t_phase = y_t_phase % (2 * np.pi) # Inverse FFT yw = np.real(fftshift(ifft(Y))) # Overlap-add and apply synth window y[p_out:p_out + n] += sw * yw p_out += h # delete half of first window... y = np.delete(y, range(h_n)) # ...and half of last window y = np.delete(y, range(y.size - h_n, y.size)) return y
def create_synth_window(N, H): hN = N / 2 sw = np.zeros(N) # initialize synthesis window ow = triang(2 * H) # triangular window sw[hN - H:hN + H] = ow # add triangular window bh = blackmanharris(N) # blackman-harris window bh = bh / sum(bh) # normalized window sw[hN - H:hN + H] = sw[hN - H:hN + H] / bh[hN - H:hN + H] # normalized synthesis window return sw
def hpsModelSynth(hfreq, hmag, hphase, mYst, N, H, fs): # Synthesis of a sound using the harmonic plus stochastic model # hfreq: harmonic frequencies, hmag:harmonic amplitudes, mYst: stochastic envelope # Ns: synthesis FFT size, H: hop size, fs: sampling rate # y: output sound, yh: harmonic component, yst: stochastic component hN = N/2 # half of FFT size for synthesis L = hfreq[:,0].size # number of frames nH = hfreq[0,:].size # number of harmonics pout = 0 # initialize output sound pointer ysize = H*(L+4) # output sound size yhw = np.zeros(N) # initialize output sound frame ysw = np.zeros(N) # initialize output sound frame yh = np.zeros(ysize) # initialize output array yst = np.zeros(ysize) # initialize output array sw = np.zeros(N) ow = triang(2*H) # overlapping window sw[hN-H:hN+H] = ow bh = blackmanharris(N) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hN-H:hN+H] = sw[hN-H:hN+H] / bh[hN-H:hN+H] # synthesis window for harmonic component sws = H*hanning(N)/2 # synthesis window for stochastic component lastyhfreq = hfreq[0,:] # initialize synthesis harmonic frequencies yhphase = 2*np.pi*np.random.rand(nH) # initialize synthesis harmonic phases for l in range(L): yhfreq = hfreq[l,:] # synthesis harmonics frequencies yhmag = hmag[l,:] # synthesis harmonic amplitudes mYrenv = mYst[l,:] # synthesis residual envelope if (hphase.size > 0): yhphase = hphase[l,:] else: yhphase += (np.pi*(lastyhfreq+yhfreq)/fs)*H # propagate phases lastyhfreq = yhfreq Yh = UF.genSpecSines(yhfreq, yhmag, yhphase, N, fs) # generate spec sines mYs = resample(mYrenv, hN) # interpolate to original size mYs = 10**(mYs/20) # dB to linear magnitude pYs = 2*np.pi*np.random.rand(hN) # generate phase random values Ys = np.zeros(N, dtype = complex) Ys[:hN] = mYs * np.exp(1j*pYs) # generate positive freq. Ys[hN+1:] = mYs[:0:-1] * np.exp(-1j*pYs[:0:-1]) # generate negative freq. fftbuffer = np.zeros(N) fftbuffer = np.real(ifft(Yh)) # inverse FFT of harm spectrum yhw[:hN-1] = fftbuffer[hN+1:] # undo zer-phase window yhw[hN-1:] = fftbuffer[:hN+1] fftbuffer = np.zeros(N) fftbuffer = np.real(ifft(Ys)) # inverse FFT of stochastic approximation spectrum ysw[:hN-1] = fftbuffer[hN+1:] # undo zero-phase window ysw[hN-1:] = fftbuffer[:hN+1] yh[pout:pout+N] += sw*yhw # overlap-add for sines yst[pout:pout+N] += sws*ysw # overlap-add for stoch pout += H # advance sound pointer y = yh+yst # sum harmonic and stochastic components return y, yh, yst
def create_triangle_trace(sampling_rate=40.0, duration=5.0, **header_kwargs): header = { 'sampling_rate': sampling_rate, 'starttime': UTCDateTime(0), 'channel': 'Z', 'station': 'test' } header = {**header, **header_kwargs} x = np.linspace(0, duration, num=int(duration * sampling_rate)) data = signal.triang(int(duration * sampling_rate)) trace = Trace(data=data, header=header) trace.stats.data_type = 'test' return Stream(traces=[trace])
def find_node_centers(similarity_profile, peak_thr=1, filter_w=13): node_centers = dict() triang_w = triang(filter_w) / (filter_w/2) for name, vec in similarity_profile.items(): filtered_vec = convolve(vec, triang_w, mode='same' ) peaks = find_peaks(filtered_vec, height=peak_thr) node_centers[name] = peaks[0] return node_centers
def triang_template(): # a = np.arange(0,50,2, dtype=int) # b = np.arange(48,-1,-2, dtype=int) # c = np.zeros(20, dtype=int) a = signal.triang(21) c = np.zeros(10) d = np.concatenate([a, c]) d2 = d[::-1] #flip d2 = -d2 e = np.concatenate([d, d2]) # e2 = e[::-1] # e = np.concatenate([a, b]) return sum(d), e
def convolve(specratio, tr, stf='triangular', filterlim=None, trim=None): from scipy.signal import triang, convolve edata = specratio.egftr pick_small = edata.stats.starttime + 2. ts1 = edata.copy() if trim: ts1.trim(starttime=pick_small + trim[0], endtime=pick_small + trim[1]) if filterlim: ts1.filter(type='bandpass', freqmin=filterlim[0], freqmax=filterlim[1]) if stf == 'triangular': n = tr * edata.stats.sampling_rate tstf = triang(round(n)) return convolve(ts1, tstf)
def FILTERDesign(Filter, fc1, fc2, window,T): x,n = sinc(fc1,T) win = np.ones(len(n)) if(window == "hamming"): win = sig.hamming(len(n)) if(window == "hanning"): win = sig.hanning(len(n)) if(window == "blackman"): win = sig.blackman(len(n)) if(window == "triangular"): win = sig.triang(len(n)) if(Filter == "LPF"): # Low pass filter x,n = sinc(fc1,T) X,w = fft(x*win,n) return X/max(X),w if(Filter == "HPF"): # High Pass Filter x,n = sinc(np.pi-fc1,T) X,w = fft(x*win,n) X = X/max(X) return np.flip(X),w if(Filter == "BPF"): # Band Pass filter f1 = fc1 f2 = fc2 if(f1<f2): x1,n1 = sinc(np.pi-f1,T) x2,n2 = sinc(f2,T) X1,w = fft(x1*win,n1) X2,w = fft(x2*win,n2) X1 = X1/max(X1) X2 = X2/max(X2) return (np.flip(X1)*X2)/max(np.flip(X1)*X2),w if(Filter == "BRF"): # Band Pass filter f1 = fc1 f2 = fc2 if(f1<f2): x1,n1 = sinc(f1,T) x2,n2 = sinc(np.pi-f2,T) X1,w = fft(x1*win,n1) X2,w = fft(x2*win,n2) X1 = X1/max(X1) X2 = X2/max(X2) return (np.flip(X2)+(X1))/max(np.flip(X2)+X1),w
def sineModelMultiRes(x, fs, wList, NList, t, BList): """ Analysis/synthesis of a sound using the sinusoidal model, without sine tracking x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB returns y: output array sound """ #-----synthesis params init----- Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 # half of synthesis FFT size yw = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # triangular window sw[hNs-H:hNs+H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # normalized synthesis window for i in range(3): #-----analysis params init----- w = wList[i] N = NList[i] Bmin = BList[i][0] Bmax = BList[i][1] hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor pin = max(hNs, hM1) # init sound pointer in middle of anal window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT w = w / sum(w) # normalize analysis window while pin<pend: # while input sound pointer is within sound #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, N) # compute dft ploc = UF.peakDetection(mX, t) # detect locations of peaks iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values by interpolation ipfreq = fs*iploc/float(N) # convert peak locations to Hertz ipmag = ipmag[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)] ipphase = ipphase[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)] ipfreq = ipfreq[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)] #-----synthesis----- Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs) # generate sines in the spectrum fftbuffer = np.real(ifft(Y)) # compute inverse FFT yw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yw[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yw # overlap-add and apply a synthesis window pin += H # advance sound pointer return y
def sineModel(x, fs, w, N, t): # Analysis/synthesis of a sound using the sinusoidal model # x: input array sound, w: analysis window, N: size of complex spectrum, # t: threshold in negative dB # returns y: output array sound hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 # half of synthesis FFT size pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yw = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H); # triangular window sw[hNs-H:hNs+H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # normalized synthesis window while pin<pend: # while input sound pointer is within sound #-----analysis----- xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT mX = 20 * np.log10( abs(X[:hN]) ) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) # detect locations of peaks pmag = mX[ploc] # get the magnitude of the peaks pX = np.unwrap( np.angle(X[:hN]) ) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values by interpolation #-----synthesis----- plocs = iploc*Ns/N; # adapt peak locations to size of synthesis FFT Y = GS.genSpecSines(plocs, ipmag, ipphase, Ns) # generate sines in the spectrum fftbuffer = np.real( ifft(Y) ) # compute inverse FFT yw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yw[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yw # overlap-add and apply a synthesis window pin += H # advance sound pointer return y
def sineModelMultiRes(x, fs, w, N, t, B): """ Analysis/synthesis of a sound using the sinusoidal model, without sine tracking x: input array sound, w: array of analysis windows, N: array of sizes of complex spectrum, t: threshold in negative dB, B: array of frequency bands returns y: output array sound """ hM1 = [int(math.floor((_w.size + 1) / 2)) for _w in w] # half analysis window(s) size by rounding hM2 = [int(math.floor(_w.size / 2)) for _w in w] # half analysis window(s) size by floor Ns = 512 # FFT size for synthesis (even) H = Ns / 4 # Hop size used for analysis and synthesis hNs = Ns / 2 # half of synthesis FFT size pin = max(hNs, max(hM1)) # init sound pointer in middle of anal window pend = x.size - max(hNs, max(hM1)) # last sample to start a frame fftbuffer = np.array([]) # initialize buffer for FFT yw = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array w = [_w / sum(_w) for _w in w] # normalize analysis window(s) sw = np.zeros(Ns) # initialize synthesis window ow = triang(2 * H) # triangular window sw[hNs - H : hNs + H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs - H : hNs + H] = sw[hNs - H : hNs + H] / bh[hNs - H : hNs + H] # normalized synthesis window while pin < pend: # while input sound pointer is within sound # -----analysis----- ipmag = ipphase = ipfreq = np.array([]) # initialize the synthesis arrays for i in range(0, len(w)): # for each window, use some loop variables ('_' prefix) _hM1, _hM2, _w, _N, _B = (hM1[i], hM2[i], w[i], N[i], B[i]) x1 = x[pin - _hM1 : pin + _hM2] # select frame mX, pX = DFT.dftAnal(x1, _w, _N) # compute dft ploc = UF.peakDetection(mX, t) # detect locations of peaks iploc, _ipmag, _ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values by interpolation _ipfreq = fs * iploc / float(_N) # convert peak locations to Hertz lo, hi = (_B[0], _B[1]) # low/high from band tuples [..(lo, hi)..] mask = (_ipfreq >= lo) * (_ipfreq < hi) # mask for in-band components ipmag = np.append(ipmag, _ipmag * mask) # mask and append components ipphase = np.append(ipphase, _ipphase * mask) ipfreq = np.append(ipfreq, _ipfreq * mask) # -----synthesis----- Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs) # generate sines in the spectrum fftbuffer = np.real(ifft(Y)) # compute inverse FFT yw[: hNs - 1] = fftbuffer[hNs + 1 :] # undo zero-phase window yw[hNs - 1 :] = fftbuffer[: hNs + 1] y[pin - hNs : pin + hNs] += sw * yw # overlap-add and apply a synthesis window pin += H # advance sound pointer return y
def ConvSilence( inXArray, inYArray, samplingRate ): if inXArray.size != inYArray.size: print "Error in ConvSilence: Dimensions must agree" return [ None, None, None, None ] #convWin = numpy.ones( WINDOW_WIDTH * samplingRate ) convWin = signal.triang( WINDOW_WIDTH * samplingRate ) starProduct = numpy.convolve( abs(inYArray), convWin, 'same' ) starProduct = starProduct / max(starProduct) silenceList = starProduct < NORM_CONV_THRESH threshold = SIL_THRESH * samplingRate silence = True silList = [] for i in range(silenceList.size): risingEdge = silence and not silenceList[i] fallingEdge = not silence and silenceList[i] if (risingEdge or fallingEdge): silence = not silence if ( len(silList) > 0 and i - silList[-1] < threshold ): silList.pop() else: silList.append(i) toRetX = numpy.split(inXArray,silList) toRetY = numpy.split(inYArray,silList) #now we split between evens and odds #because we have silence=True to start, #the evens are silent, and the odds are not silentX = toRetX[::2] silentY = toRetY[::2] speakX = toRetX[1::2] speakY = toRetY[1::2] #print "reading "+str(i+1)+" has "+str(len(silList)/2)+" pauses" return [ silentX, silentY, speakX, speakY ]
def gain_norm(stream, N): stream2 = copy.deepcopy(stream) for trace in arange(len(stream2)): data = stream2[trace].data dt = 1./(stream2[trace].stats.sampling_rate) L = floor((N/dt+1./2.)) h = triang(2.*L+1.) e = data**2. rms = (convolve(e,h,'same')**0.5) epsilon = 1.e-12*amax(rms) op = rms/(rms**2+epsilon) dout = data*op stream2[trace].data = dout return stream2
def gen_window(window_type, window_size, sym=True): """ Generates a window function of given size and type Returns a 1D numpy array sym: Used in the triangle window generation. When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis Available window types: - hanning - hamming - bartlett - blackman - kaiser - triangle """ if window_type is "hanning": return np.hanning(window_size) elif window_type is "hamming": return np.hamming(window_size) elif window_type is "bartlett": return np.bartlett(window_size) elif window_type is "blackman": return np.blackman(window_size) elif window_type is "kaiser": return np.kaiser(window_size) elif window_type is "triangle": return signal.triang(window_size, sym=sym) else: raise ValueError("'{0}' is not a valid window" " type".format(window_type))
def cqtfft(X, fs=44100, lo=12, hi=None): """ q, p = cqtfft(X, fs) Returns the complex constant-Q transform vector of fft vector X with sampling rate FS. Like chroma, but unwrapped. Here, Q = 16.817. """ if X.ndim==2: X = X[:,0].squeeze() if hi is None: hi = int(hz2midi(fs/2)) p = scipy.arange(lo, hi) q = scipy.zeros(hi-lo) for i,midi in enumerate(p): center = X.size*midi2hz(midi)/fs width = int(center/16.817) center = int(center) w = ss.triang(2*width+1) q[i] = scipy.inner(w, X[center-width:center+width+1]) return q, p
def harmonicModel(x, fs, w, N, t, nH, minf0, maxf0, f0et, maxhd, maxnpeaksTwm=10): # Analysis/synthesis of a sound using the sinusoidal harmonic model # x: input sound, fs: sampling rate, w: analysis window, # N: FFT size (minimum 512), t: threshold in negative dB, # nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, # maxf0: maximim f0 frequency in Hz, # f0et: error threshold in the f0 detection (ex: 5), # maxhd: max. relative deviation in harmonic detection (ex: .2) # maxnpeaksTwm: maximum number of peaks used for F0 detection # yh: harmonic component, yr: residual component # returns y: output array sound hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yh = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] while pin<pend: #-----analysis----- xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT mX = 20 * np.log10( abs(X[:hN]) ) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) # detect peak locations pX = np.unwrap( np.angle(X[:hN]) ) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values f0 = fd.f0DetectionTwm(iploc, ipmag, N, fs, f0et, minf0, maxf0, maxnpeaksTwm) # find f0 hloc = np.zeros(nH) # initialize harmonic locations hmag = np.zeros(nH)-100 # initialize harmonic magnitudes hphase = np.zeros(nH) # initialize harmonic phases hf = (f0>0)*(f0*np.arange(1, nH+1)) # initialize harmonic frequencies hi = 0 # initialize harmonic index npeaks = ploc.size # number of peaks found while f0>0 and hi<nH and hf[hi]<fs/2 : # find harmonic peaks dev = min(abs(iploc/N*fs - hf[hi])) pei = np.argmin(abs(iploc/N*fs - hf[hi])) # closest peak if ( hi==0 or not any(hloc[:hi]==iploc[pei]) ) and dev<maxhd*hf[hi] : hloc[hi] = iploc[pei] # harmonic locations hmag[hi] = ipmag[pei] # harmonic magnitudes hphase[hi] = ipphase[pei] # harmonic phases hi += 1 # increase harmonic index hloc = (hloc!=0) * (hloc*Ns/N) # synth. locs #-----synthesis----- Yh = GS.genSpecSines(hloc, hmag, hphase, Ns) # generate spec sines fftbuffer = np.real( ifft(Yh) ) # inverse FFT yh[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yh[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yh # overlap-add pin += H # advance sound pointer return y
def filter_csd(self, csd, filterfunction='convolve'): ''' Spatial filtering of the CSD estimate, using an N-point filter Arguments --------- csd : np.ndarrray * quantity.Quantity Array with the csd estimate filterfunction : str 'filtfilt' or 'convolve'. Apply spatial filter using scipy.signal.filtfilt or scipy.signal.convolve. ''' if self.f_type == 'gaussian': try: assert(len(self.f_order) == 2) except AssertionError as ae: raise ae('filter order f_order must be a tuple of length 2') else: try: assert(self.f_order > 0 and isinstance(self.f_order, int)) except AssertionError as ae: raise ae('Filter order must be int > 0!') try: assert(filterfunction in ['filtfilt', 'convolve']) except AssertionError as ae: raise ae("{} not equal to 'filtfilt' or \ 'convolve'".format(filterfunction)) if self.f_type == 'boxcar': num = ss.boxcar(self.f_order) denom = np.array([num.sum()]) elif self.f_type == 'hamming': num = ss.hamming(self.f_order) denom = np.array([num.sum()]) elif self.f_type == 'triangular': num = ss.triang(self.f_order) denom = np.array([num.sum()]) elif self.f_type == 'gaussian': num = ss.gaussian(self.f_order[0], self.f_order[1]) denom = np.array([num.sum()]) elif self.f_type == 'identity': num = np.array([1.]) denom = np.array([1.]) else: print('%s Wrong filter type!' % self.f_type) raise num_string = '[ ' for i in num: num_string = num_string + '%.3f ' % i num_string = num_string + ']' denom_string = '[ ' for i in denom: denom_string = denom_string + '%.3f ' % i denom_string = denom_string + ']' print(('discrete filter coefficients: \nb = {}, \ \na = {}'.format(num_string, denom_string))) if filterfunction == 'filtfilt': return ss.filtfilt(num, denom, csd, axis=0) * csd.units elif filterfunction == 'convolve': csdf = csd / csd.units for i in range(csdf.shape[1]): csdf[:, i] = ss.convolve(csdf[:, i], num / denom.sum(), 'same') return csdf * csd.units
import matplotlib.pyplot as plt import numpy as np from scipy.signal import hamming, triang, blackmanharris triangle = np.zeros (70) triangle[1:32] = triang (31) rectangle = np.zeros (70) rectangle[1:32] = np.ones (31) output = np.zeros (70) output = np.convolve(triangle, rectangle) plt.figure(1) plt.subplot(3, 1, 1) plt.plot(triangle) plt.axis([0,69,-.1,1.1]) plt.title ('triangle') plt.subplot(3, 1, 2) plt.plot(rectangle) plt.axis([0,69,-.1,1.1]) plt.title ('rectangle') plt.subplot(3, 1, 3) plt.plot(output) plt.axis([0,69,-1,17]) plt.title ('triangle * rectangle') plt.show()
def hpsModelSpectrogramPlot(x, fs, w, N, t, nH, minf0, maxf0, f0et, maxhd, stocf, maxFreq): hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yhw = np.zeros(Ns) # initialize output sound frame yrw = np.zeros(Ns) # initialize output sound frame yh = np.zeros(x.size) # initialize output array yr = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] numFrames = int(math.floor(pend/float(H))) frmNum = 0 frmTime = [] lastBin = N*maxFreq/float(fs) binFreq = np.arange(lastBin)*float(fs)/N # The bin frequencies while pin<pend: # while sound pointer is smaller than last sample frmTime.append(pin/float(fs)) xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT mX = 20 * np.log10(abs(X[:hN])) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) pX = np.unwrap(np.angle(X[:hN])) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values f0 = fd.f0DetectionTwm(iploc, ipmag, N, fs, f0et, minf0, maxf0) # find f0 hloc = np.zeros(nH) # initialize harmonic locations hmag = np.zeros(nH)-100 # initialize harmonic magnitudes hphase = np.zeros(nH) # initialize harmonic phases hf = (f0>0)*(f0*np.arange(1, nH+1)) # initialize harmonic frequencies hi = 0 # initialize harmonic index npeaks = ploc.size; # number of peaks found while f0>0 and hi<nH and hf[hi]<fs/2 : # find harmonic peaks dev = min(abs(iploc/N*fs - hf[hi])) pei = np.argmin(abs(iploc/N*fs - hf[hi])) # closest peak if ( hi==0 or not any(hloc[:hi]==iploc[pei]) ) and dev<maxhd*hf[hi] : hloc[hi] = iploc[pei] # harmonic locations hmag[hi] = ipmag[pei] # harmonic magnitudes hphase[hi] = ipphase[pei] # harmonic phases hi += 1 # increase harmonic index if frmNum == 0: # Accumulate and store STFT XSpec = np.transpose(np.array([mX[:lastBin]])) ind1 = np.where(hloc>0)[0] ind2 = np.where(hloc<=lastBin)[0] ind = list((set(ind1.tolist())&set(ind2.tolist()))) final_peaks = hloc[ind] parray = np.zeros([final_peaks.size,2]) parray[:,0]=pin/float(fs) parray[:,1]=final_peaks*float(fs)/N specPeaks = parray else: XSpec = np.hstack((XSpec,np.transpose(np.array([mX[:lastBin]])))) ind1 = np.where(hloc>0)[0] ind2 = np.where(hloc<=lastBin)[0] ind = list((set(ind1.tolist())&set(ind2.tolist()))) final_peaks = hloc[ind] parray = np.zeros([final_peaks.size,2]) parray[:,0]=pin/float(fs) parray[:,1]=final_peaks*float(fs)/N specPeaks = np.append(specPeaks, parray,axis=0) hloc[:hi] = (hloc[:hi]!=0) * (hloc[:hi]*Ns/N) # synth. locs ri = pin-hNs-1 # input sound pointer for residual analysis xr = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xr[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xr[:hNs] Xr = fft(fftbuffer) # compute FFT for residual analysis Yh = GS.genSpecSines(hloc[:hi], hmag, hphase, Ns) # generate spec sines of harmonic component Yr = Xr-Yh; # get the residual complex spectrum mYr = 20 * np.log10(abs(Yr[:hNs])) mYrenv = resample(np.maximum(-200, mYr), mYr.size*stocf) # decimate the magnitude spectrum and avoid -Inf mYs = resample(mYrenv, hNs) lastBinYr = Ns*maxFreq/float(fs) binFreqYr = np.arange(lastBinYr)*float(fs)/Ns # The bin frequencies if frmNum == 0: # Accumulate and store STFT YrSpec = np.transpose(np.array([mYr[:lastBinYr]])) YsSpec = np.transpose(np.array([mYs[:lastBinYr]])) else: YrSpec = np.hstack((YrSpec,np.transpose(np.array([mYr[:lastBinYr]])))) YsSpec = np.hstack((YsSpec,np.transpose(np.array([mYs[:lastBinYr]])))) pin += H frmNum += 1 frmTime = np.array(frmTime) # The time at the centre of the frames plt.figure(1) plt.subplot(3,1,1) plt.pcolormesh(frmTime,binFreq,XSpec) plt.scatter(specPeaks[:,0]+(0.5*H/float(fs)), specPeaks[:,1], s=10, marker='x') plt.autoscale(tight=True) plt.title('X spectrogram + peaks') plt.subplot(3,1,2) plt.pcolormesh(frmTime,binFreqYr,YrSpec) plt.autoscale(tight=True) plt.title('X residual spectrogram') plt.subplot(3,1,3) plt.pcolormesh(frmTime,binFreqYr,YsSpec) plt.autoscale(tight=True) plt.title('X residual stochastic approx. spectrogram') plt.show() return YSpec
def sineModelMultiRes_combined(x, fs, multi_w, multi_N, t, multi_B): """ Analysis/synthesis of a sound using the sinusoidal model, without sine tracking x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB returns y: output array sound """ # fallback for original code w = multi_w[0] N = multi_N[0] bands = range(len(multi_B)) # to iterate over bands #-orig----------------------------- hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor #-multi---------------------------- multi_w_size = np.array([multi_w[i].size for i in bands]) multi_hM1 = np.floor((multi_w_size + 1)/2.0).astype(int) # half analysis window size by rounding multi_hM2 = np.floor(multi_w_size / 2.0).astype(int) # half analysis window size by floor #---------------------------------- Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 # half of synthesis FFT size #-orig----------------------------- pin = max(hNs, hM1) # init sound pointer in middle of anal window pend = x.size - max(hNs, hM1) # last sample to start a frame #-multi---------------------------- multi_pin = np.maximum(hNs, multi_hM1) # init sound pointer in middle of anal window multi_pend = x.size - multi_pin # last sample to start a frame #---------------------------------- #-orig----------------------------- fftbuffer = np.zeros(N) # initialize buffer for FFT #-multi---------------------------- fftbuffer_combined = np.zeros(N) #multi_fftbuffer = [np.array(multi_N[i]) for i in bands] #---------------------------------- yw = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array #-multi---------------------------- yw_combined = np.zeros(Ns) # initialize output sound frame y_combined = np.zeros(x.size) # initialize output array #-orig----------------------------- w = w / sum(w) # normalize analysis window #-multi---------------------------- multi_w = [multi_w[i] / sum(multi_w[i]) for i in bands] # normalize analysis window #---------------------------------- sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # triangular window sw[hNs-H:hNs+H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # normalized synthesis window while pin<pend and (multi_pin<multi_pend).all(): # while input sound pointer is within sound #-----analysis----- #-orig----------------------------- x1 = x[pin-hM1:pin+hM2] # select frame #-multi---------------------------- multi_x1 = [x[(multi_pin[i] - multi_hM1[i]) : (multi_pin[i] + multi_hM2[i])] for i in bands] # select frame #---------------------------------- #-orig----------------------------- mX, pX = DFT.dftAnal(x1, w, N) # compute dft #-multi---------------------------- multi_mX = [] multi_pX = [] for i in bands: mXi, pXi = DFT.dftAnal(multi_x1[i], multi_w[i], multi_N[i]) multi_mX.append(mXi) multi_pX.append(pXi) #---------------------------------- # we could apply the filters for the bands here already ... #-orig----------------------------- ploc = UF.peakDetection(mX, t) # detect locations of peaks #pmag = mX[ploc] # get the magnitude of the peaks #-multi---------------------------- multi_ploc = [] #multi_pmag = [] for i in bands: ploci = UF.peakDetection(multi_mX[i], t) # detect locations of peaks #pmagi = multi_mX[i][ploci] # get the magnitude of the peaks multi_ploc.append(ploci) #multi_pmag.append(pmagi) #---------------------------------- #-orig----------------------------- iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values by interpolation ipfreq = fs*iploc/float(N) # convert peak locations to Hertz #-multi---------------------------- #multi_iploc = [] multi_ipmag = [] multi_ipphase = [] multi_ipfreq = [] for i in bands: iploci, ipmagi, ipphasei = UF.peakInterp(multi_mX[i], multi_pX[i], multi_ploc[i]) # refine peak values by interpolation ipfreqi = fs*iploci/float(multi_N[i]) # convert peak locations to Hertz #multi_iploc.append(iploci) multi_ipmag.append(ipmagi) multi_ipphase.append(ipphasei) multi_ipfreq.append(ipfreqi) #---------------------------------- # ... but we shall decide here! """ print "--------------------------------------" print ipfreq print ipmag print ipphase """ """ ipfreq_combined = [] ipmag_combined = [] ipphase_combined = [] for i in bands: for p in range(len(multi_ipfreq[i])): f = multi_ipfreq[i][p] if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]: ipfreq_combined.append(f) ipmag_combined.append(multi_ipmag[i][p]) ipphase_combined.append(multi_ipphase[i][p]) #ipfreq = np.array(ipfreq_combined) #ipmag = np.array(ipmag_combined) #ipphase = np.array(ipphase_combined) """ # count first for array allocation num_ip = 0 for i in bands: for p in range(len(multi_ipfreq[i])): f = multi_ipfreq[i][p] if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]: num_ip += 1 ipfreq_combined = np.zeros(num_ip) ipmag_combined = np.zeros(num_ip) ipphase_combined = np.zeros(num_ip) ip = 0 for i in bands: for p in range(len(multi_ipfreq[i])): f = multi_ipfreq[i][p] if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]: ipfreq_combined[ip] = f ipmag_combined[ip] = multi_ipmag[i][p] ipphase_combined[ip] = multi_ipphase[i][p] ip += 1 """ print "--------------------------------------" print ipfreq_combined print ipmag_combined print ipphase_combined """ #-----synthesis----- Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs) # generate sines in the spectrum fftbuffer = np.real(ifft(Y)) # compute inverse FFT yw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yw[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yw # overlap-add and apply a synthesis window #print y[pin-hNs:pin+hNs] pin += H # advance sound pointer Y_combined = UF.genSpecSines(ipfreq_combined, ipmag_combined, ipphase_combined, Ns, fs) # generate sines in the spectrum fftbuffer_combined = np.real(ifft(Y_combined)) # compute inverse FFT yw_combined[:hNs-1] = fftbuffer_combined[hNs+1:] # undo zero-phase window yw_combined[hNs-1:] = fftbuffer_combined[:hNs+1] y_combined[pin-hNs:pin+hNs] += sw*yw_combined # overlap-add and apply a synthesis window #print y_combined[pin-hNs:pin+hNs] multi_pin += H """ plt.figure(1) plt.plot(abs(Y)) plt.figure(2) plt.plot(abs(Y_combined)) plt.show() """ return y, y_combined
def hpsModel(x, fs, w, N, t, nH, minf0, maxf0, f0et, stocf): """ Analysis/synthesis of a sound using the harmonic plus stochastic model, one frame at a time, no harmonic tracking x: input sound; fs: sampling rate, w: analysis window; N: FFT size (minimum 512), t: threshold in negative dB, nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz; maxf0: maximim f0 frequency in Hz, f0et: error threshold in the f0 detection (ex: 5); stocf: decimation factor of mag spectrum for stochastic analysis returns y: output sound, yh: harmonic component, yst: stochastic component """ hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yhw = np.zeros(Ns) # initialize output sound frame ystw = np.zeros(Ns) # initialize output sound frame yh = np.zeros(x.size) # initialize output array yst = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # synthesis window for harmonic component sws = H*hanning(Ns)/2 # synthesis window for stochastic hfreqp = [] f0t = 0 f0stable = 0 while pin<pend: #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, N) # compute dft ploc = UF.peakDetection(mX, t) # find peaks iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values ipfreq = fs * iploc/N # convert peak locations to Hz f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable) # find f0 if ((f0stable==0)&(f0t>0)) \ or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)): f0stable = f0t # consider a stable f0 if it is close to the previous one else: f0stable = 0 hfreq, hmag, hphase = HM.harmonicDetection(ipfreq, ipmag, ipphase, f0t, nH, hfreqp, fs) # find harmonics hfreqp = hfreq ri = pin-hNs-1 # input sound pointer for residual analysis xw2 = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xw2[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xw2[:hNs] X2 = fft(fftbuffer) # compute FFT for residual analysis #-----synthesis----- Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns, fs) # generate spec sines of harmonic component Xr = X2-Yh # get the residual complex spectrum mXr = 20 * np.log10(abs(Xr[:hNs])) # magnitude spectrum of residual mXrenv = resample(np.maximum(-200, mXr), mXr.size*stocf) # decimate the magnitude spectrum and avoid -Inf stocEnv = resample(mXrenv, hNs) # interpolate to original size pYst = 2*np.pi*np.random.rand(hNs) # generate phase random values Yst = np.zeros(Ns, dtype = complex) Yst[:hNs] = 10**(stocEnv/20) * np.exp(1j*pYst) # generate positive freq. Yst[hNs+1:] = 10**(stocEnv[:0:-1]/20) * np.exp(-1j*pYst[:0:-1]) # generate negative freq. fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yh)) # inverse FFT of harmonic spectrum yhw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yhw[hNs-1:] = fftbuffer[:hNs+1] fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yst)) # inverse FFT of stochastic spectrum ystw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window ystw[hNs-1:] = fftbuffer[:hNs+1] yh[ri:ri+Ns] += sw*yhw # overlap-add for sines yst[ri:ri+Ns] += sws*ystw # overlap-add for stochastic pin += H # advance sound pointer y = yh+yst # sum of harmonic and stochastic components return y, yh, yst
def spsModel(x, fs, w, N, t, stocf): # Analysis/synthesis of a sound using the sinusoidal plus residual model # x: input sound, fs: sampling rate, w: analysis window, # N: FFT size (minimum 512), t: threshold in negative dB, # stocf: decimation factor of mag spectrum for stochastic analysis # y: output sound, ys: sinusoidal component, yr: residual component hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT ysw = np.zeros(Ns) # initialize output sound frame ystw = np.zeros(Ns) # initialize output sound frame ys = np.zeros(x.size) # initialize output array yst = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] while pin<pend: #-----analysis----- xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT mX = 20 * np.log10(abs(X[:hN])) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) pX = np.unwrap(np.angle(X[:hN])) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values iploc = (iploc!=0) * (iploc*Ns/N) # synth. locs ri = pin-hNs-1 # input sound pointer for residual analysis xr = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xr[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xr[:hNs] Xr = fft(fftbuffer) # compute FFT for residual analysis #-----synthesis----- Ys = GS.genSpecSines(iploc, ipmag, ipphase, Ns) # generate spec of sinusoidal component Yr = Xr-Ys; # get the residual complex spectrum mYr = 20 * np.log10( abs(Yr[:hNs]) ) # magnitude spectrum of residual mYrenv = resample(np.maximum(-200, mYr), mYr.size*stocf) # decimate the magnitude spectrum and avoid -Inf mYst = resample(mYrenv, hNs) # interpolate to original size mYst = 10**(mYst/20) # dB to linear magnitude fc = 1+round(500.0/fs*Ns) # 500 Hz to bin location mYst[:fc] *= (np.arange(0, fc)/(fc-1))**2 # high pass filter the stochastic component pYst = 2*np.pi*np.random.rand(hNs) # generate phase random values Yst = np.zeros(Ns, dtype = complex) Yst[:hNs] = mYst * np.exp(1j*pYst) # generate positive freq. Yst[hNs+1:] = mYst[:0:-1] * np.exp(-1j*pYst[:0:-1]) # generate negative freq. fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Ys)) # inverse FFT of sinusoidal spectrum ysw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window ysw[hNs-1:] = fftbuffer[:hNs+1] fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yst)) # inverse FFT of residual spectrum ystw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window ystw[hNs-1:] = fftbuffer[:hNs+1] ys[ri:ri+Ns] += sw*ysw # overlap-add for sines yst[ri:ri+Ns] += sw*ystw # overlap-add for residual pin += H # advance sound pointer y = ys+yst # sum of sinusoidal and residual components return y, ys, yst
def sineModelMultiRes(x, fs, multi_w, multi_N, t, multi_B): """ Analysis/synthesis of a sound using the sinusoidal model, without sine tracking x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB returns y: output array sound """ bands = range(len(multi_B)) # to iterate over bands N = max(multi_N) multi_w_size = np.array([multi_w[i].size for i in bands]) multi_hM1 = np.floor((multi_w_size + 1)/2.0).astype(int) # half analysis window size by rounding multi_hM2 = np.floor(multi_w_size / 2.0).astype(int) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 # half of synthesis FFT size multi_pin = np.maximum(hNs, multi_hM1) # init sound pointer in middle of anal window multi_pend = x.size - multi_pin # last sample to start a frame fftbuffer_combined = np.zeros(N) yw_combined = np.zeros(Ns) # initialize output sound frame y_combined = np.zeros(x.size) # initialize output array multi_w = [multi_w[i] / sum(multi_w[i]) for i in bands] # normalize analysis window sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # triangular window sw[hNs-H:hNs+H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # normalized synthesis window while (multi_pin<multi_pend).all(): # while input sound pointer is within sound #-----analysis----- multi_x1 = [x[(multi_pin[i] - multi_hM1[i]) : (multi_pin[i] + multi_hM2[i])] for i in bands] # select frame multi_mX = [] multi_pX = [] for i in bands: mXi, pXi = DFT.dftAnal(multi_x1[i], multi_w[i], multi_N[i]) multi_mX.append(mXi) multi_pX.append(pXi) multi_ploc = [] for i in bands: ploci = UF.peakDetection(multi_mX[i], t) # detect locations of peaks multi_ploc.append(ploci) multi_ipmag = [] multi_ipphase = [] multi_ipfreq = [] for i in bands: iploci, ipmagi, ipphasei = UF.peakInterp(multi_mX[i], multi_pX[i], multi_ploc[i]) # refine peak values by interpolation ipfreqi = fs*iploci/float(multi_N[i]) # convert peak locations to Hertz multi_ipmag.append(ipmagi) multi_ipphase.append(ipphasei) multi_ipfreq.append(ipfreqi) # count first for array allocation num_ip = 0 for i in bands: for p in range(len(multi_ipfreq[i])): f = multi_ipfreq[i][p] if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]: num_ip += 1 ipfreq_combined = np.zeros(num_ip) ipmag_combined = np.zeros(num_ip) ipphase_combined = np.zeros(num_ip) ip = 0 for i in bands: for p in range(len(multi_ipfreq[i])): f = multi_ipfreq[i][p] if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]: ipfreq_combined[ip] = f ipmag_combined[ip] = multi_ipmag[i][p] ipphase_combined[ip] = multi_ipphase[i][p] ip += 1 #-----synthesis----- Y_combined = UF.genSpecSines(ipfreq_combined, ipmag_combined, ipphase_combined, Ns, fs) # generate sines in the spectrum fftbuffer_combined = np.real(ifft(Y_combined)) # compute inverse FFT yw_combined[:hNs-1] = fftbuffer_combined[hNs+1:] # undo zero-phase window yw_combined[hNs-1:] = fftbuffer_combined[:hNs+1] y_combined[multi_pin[0]-hNs:multi_pin[0]+hNs] += sw*yw_combined # overlap-add and apply a synthesis window multi_pin += H return y_combined
def hprModel(x, fs, w, N, t, nH, minf0, maxf0, f0et): """ Analysis/synthesis of a sound using the harmonic plus residual model x: input sound, fs: sampling rate, w: analysis window, N: FFT size (minimum 512), t: threshold in negative dB, nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, maxf0: maximim f0 frequency in Hz, f0et: error threshold in the f0 detection (ex: 5), maxhd: max. relative deviation in harmonic detection (ex: .2) returns y: output sound, yh: harmonic component, xr: residual component """ hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yhw = np.zeros(Ns) # initialize output sound frame xrw = np.zeros(Ns) # initialize output sound frame yh = np.zeros(x.size) # initialize output array xr = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] hfreqp = [] f0t = 0 f0stable = 0 while pin<pend: #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, N) # compute dft ploc = UF.peakDetection(mX, t) # find peaks iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values ipfreq = fs * iploc/N # convert locations to Hz f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable) # find f0 if ((f0stable==0)&(f0t>0)) \ or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)): f0stable = f0t # consider a stable f0 if it is close to the previous one else: f0stable = 0 hfreq, hmag, hphase = HM.harmonicDetection(ipfreq, ipmag, ipphase, f0t, nH, hfreqp, fs) # find harmonics hfreqp = hfreq ri = pin-hNs-1 # input sound pointer for residual analysis xw2 = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xw2[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xw2[:hNs] X2 = fft(fftbuffer) # compute FFT of input signal for residual analysis #-----synthesis----- Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns, fs) # generate sines Xr = X2-Yh # get the residual complex spectrum fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yh)) # inverse FFT of harmonic spectrum yhw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yhw[hNs-1:] = fftbuffer[:hNs+1] fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Xr)) # inverse FFT of residual spectrum xrw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window xrw[hNs-1:] = fftbuffer[:hNs+1] yh[ri:ri+Ns] += sw*yhw # overlap-add for sines xr[ri:ri+Ns] += sw*xrw # overlap-add for residual pin += H # advance sound pointer y = yh+xr # sum of harmonic and residual components return y, yh, xr
def hprModelFrame(x, fs, w, N, t, nH, minf0, maxf0, f0et, maxhd): hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window fftbuffer = np.zeros(N) # initialize buffer for FFT yhw = np.zeros(Ns) # initialize output sound frame yrw = np.zeros(Ns) # initialize output sound frame yh = np.zeros(x.size) # initialize output array yr = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] #-----analysis----- xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT mX = 20 * np.log10(abs(X[:hN])) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) pX = np.unwrap(np.angle(X[:hN])) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values f0 = fd.f0DetectionTwm(iploc, ipmag, N, fs, f0et, minf0, maxf0) # find f0 hloc = np.zeros(nH) # initialize harmonic locations hmag = np.zeros(nH)-100 # initialize harmonic magnitudes hphase = np.zeros(nH) # initialize harmonic phases hf = (f0>0)*(f0*np.arange(1, nH+1)) # initialize harmonic frequencies hi = 0 # initialize harmonic index npeaks = ploc.size; # number of peaks found while f0>0 and hi<nH and hf[hi]<fs/2 : # find harmonic peaks dev = min(abs(iploc/N*fs - hf[hi])) pei = np.argmin(abs(iploc/N*fs - hf[hi])) # closest peak if ( hi==0 or not any(hloc[:hi]==iploc[pei]) ) and dev<maxhd*hf[hi] : hloc[hi] = iploc[pei] # harmonic locations hmag[hi] = ipmag[pei] # harmonic magnitudes hphase[hi] = ipphase[pei] # harmonic phases hi += 1 # increase harmonic index hlocN = hloc hloc[:hi] = (hloc[:hi]!=0) * (hloc[:hi]*Ns/N) # synth. locs ri = pin-hNs-1 # input sound pointer for residual analysis xr = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xr[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xr[:hNs] Xr = fft(fftbuffer) # compute FFT for residual analysis #-----synthesis----- Yh = GS.genSpecSines(hloc[:hi], hmag, hphase, Ns) # generate spec sines of harmonic component mYh = 20 * np.log10(abs(Yh[:hNs])) pYh = np.unwrap(np.angle(Yh[:hNs])) Yr = Xr-Yh; # get the residual complex spectrum mXr = 20 * np.log10(abs(Xr[:hNs])) pXr = np.unwrap(np.angle(Xr[:hNs])) mYr = 20 * np.log10(abs(Yr[:hNs])) pYr = np.unwrap(np.angle(Yr[:hNs])) fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yh)) # inverse FFT of harmonic spectrum yhw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yhw[hNs-1:] = fftbuffer[:hNs+1] fftbuffer = np.zeros(Ns) fftbuffer = np.real(ifft(Yr)) # inverse FFT of residual spectrum yrw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yrw[hNs-1:] = fftbuffer[:hNs+1] yh[ri:ri+Ns] += sw*yhw # overlap-add for sines yr[ri:ri+Ns] += sw*yrw # overlap-add for residual y = yh+yr # sum of harmonic and residual components return mX, pX, hlocN, hmag, hphase, mYh, pYh, mXr, pXr, mYr, pYr, yh, yr, y
def sineModelMultiRes(x, fs, Ns, W, M, N, B, T): """ Analysis/synthesis of a sound using the multi-resolution sinusoidal model, without sine tracking x: input array sound, fs: sampling frequency, Ns: FFT size for synthesis, W: array of analysis window types, M: array of analysis windows sizes, N: array of sizes of complex spectrums, B: array of frequency bands separators (ascending order of frequency, number of bands == B.size + 1), T: array of peak detection thresholds in negative dB. returns y: output array sound """ nResolutions = W.size if (nResolutions != N.size) or (nResolutions != B.size + 1) or (nResolutions != T.size): raise ValueError('Parameters W,N,B,T shall have compatible sizes') H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 # half of synthesis FFT size yw = np.zeros(Ns) # initialize output sound frame y = np.zeros(x.size) # initialize output array sw = np.zeros(Ns) # initialize synthesis window ow = triang(2*H) # triangular window sw[hNs-H:hNs+H] = ow # add triangular window bh = blackmanharris(Ns) # blackmanharris window bh = bh / sum(bh) # normalized blackmanharris window sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] # normalized synthesis window HM1 = map(lambda m: math.floor((m+1)/2),M) # half analysis windows sizes by rounding HM2 = map(lambda m: math.floor( m /2),M) # half analysis windows sizes by floor maxHM1 = max(HM1) # max half analysis window size by rounding pin = max(hNs, maxHM1) # init sound pointers in the middle of largest window pend = x.size - pin # last samples to start a frame while pin < pend: # while input sound pointer is within sound combinedIPFreq = np.array([]) combinedIPMag = np.array([]) combinedIPhase = np.array([]) windowSizeAttribution = np.array([]) #-----multi-resolution spectrum calculation----- for k in range(0,nResolutions): windowType = W[k] windowSize = M[k] w = get_window(windowType,windowSize) # normalize analysis window w = w / sum(w) n = N[k] t = T[k] hM1 = HM1[k] # half analysis window size by rounding hM2 = HM2[k] # half analysis window size by floor #-----analysis----- x1 = x[pin-hM1:pin+hM2] # select frame mX, pX = DFT.dftAnal(x1, w, n) # compute dft ploc = UF.peakDetection(mX, t) # detect locations of peaks iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) # refine peak values by interpolation ipfreq = fs*iploc/float(n) # convert peak locations to Hertz if k == 0: # First frequency range starts from zero f0 = 0.0 else: f0 = B[k-1] if k == B.size: # Last frequency range ends at fs/2 f1 = fs / 2.0 else: f1 = B[k] for l in range(0,ipfreq.size): # Pick the peaks (no pun intended:) inside the assigned frequency band f = ipfreq[l] if f0 <= f and f < f1: combinedIPFreq = np.append(combinedIPFreq, f) combinedIPMag = np.append(combinedIPMag , ipmag [l]) combinedIPhase = np.append(combinedIPhase, ipphase[l]) windowSizeAttribution = np.append(windowSizeAttribution, windowSize) # Let's smooth out "double-reported" peaks close to the division frequencies of the frequency ranges freqDiffThreshold = (fs*6)/float(n) smoothedIPFreq = np.array([]) smoothedIPMag = np.array([]) smoothedIPhase = np.array([]) nPeaks = combinedIPFreq.size l = 0 while l < (nPeaks-1): f1 = combinedIPFreq[l] f2 = combinedIPFreq[l+1] m1 = windowSizeAttribution[l] m2 = windowSizeAttribution[l+1] freqDiff = abs(f1-f2) if freqDiff < freqDiffThreshold and m1 != m2: #print '!',f1,f2,m1,m2,freqDiff smoothedIPFreq = np.append(smoothedIPFreq, (f1+f2)/2.0) smoothedIPMag = np.append(smoothedIPMag , (combinedIPMag [l] + combinedIPMag [l+1])/2.0) smoothedIPhase = np.append(smoothedIPhase, (combinedIPhase[l] + combinedIPhase[l+1])/2.0) l = l + 2 else: smoothedIPFreq = np.append(smoothedIPFreq, f1) smoothedIPMag = np.append(smoothedIPMag , combinedIPMag [l]) smoothedIPhase = np.append(smoothedIPhase, combinedIPhase[l]) l = l + 1 # Add the last peak smoothedIPFreq = np.append(smoothedIPFreq,combinedIPFreq[nPeaks-1]) smoothedIPMag = np.append(smoothedIPMag ,combinedIPMag [nPeaks-1]) smoothedIPhase = np.append(smoothedIPhase,combinedIPhase[nPeaks-1]) #-----synthesis----- Y = UF.genSpecSines(smoothedIPFreq, smoothedIPMag, smoothedIPhase, Ns, fs) # generate sines in the spectrum fftbuffer = np.real(ifft(Y)) # compute inverse FFT yw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yw[hNs-1:] = fftbuffer[:hNs+1] y[pin-hNs:pin+hNs] += sw*yw # overlap-add and apply a synthesis window pin += H # advance sound pointer return y
Ns = 512 hNs = Ns / 2 H = Ns / 4 M = 511 t = -70 w = get_window('hamming', M) x1 = x[.8*fs:0.8*fs+M] mX, pX = DFT.dftAnal(x1, w, Ns) ploc = UF.peakDetection(mX, t) iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc) ipfreq = fs * iploc / float(Ns) Y = UF.genSpecSines_p(ipfreq, ipmag, ipphase, Ns, fs) y = np.real(ifft(Y)) sw = np.zeros(Ns) ow = triang(Ns/2) sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) bh = bh / sum(bh) sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] yw = np.zeros(Ns) yw[:hNs-1] = y[hNs+1:] yw[hNs-1:] = y[:hNs+1] yw *= sw freqaxis = fs * np.arange(Ns/2 + 1) / float(Ns) plt.plot(freqaxis, mX) plt.plot(fs * iploc / Ns, ipmag, marker = 'x', linestyle = '') plt.show()
def hpsModel(x, fs, w, N, t, nH, minf0, maxf0, f0et, maxhd, stocf) : # Analysis/synthesis of a sound using the harmonic plus stochastic model # x: input sound, fs: sampling rate, w: analysis window (odd size), # N: FFT size (minimum 512), t: threshold in negative dB, # nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, # maxf0: maximim f0 frequency in Hz, # f0et: error threshold in the f0 detection (ex: 5), # maxhd: max. relative deviation in harmonic detection (ex: .2) # stocf: decimation factor of mag spectrum for stochastic analysis # y: output sound, yh: harmonic component, ys: stochastic component x = np.float32(x) / (2**15) # normalize input signal fig = plt.figure(figsize = (10.5, 6.5), dpi = 100) ax1 = plt.subplot2grid((4, 6), (0, 1), colspan = 4) ax1.set_position([0.10, 0.77, 0.8, 0.16]) ax1.set_xlim(0, 10000) ax1.set_ylim(x.min(), x.max()) ax1.set_title("Input Signal") plt.setp(ax1.get_xticklabels(), visible = False) ax2 = plt.subplot2grid((4, 6), (1, 1), colspan = 4, sharex = ax1, sharey = ax1) ax2.set_position([0.10, 0.55, 0.8, 0.16]) ax2.set_xlim(0, 10000) ax2.set_ylim(x.min(), x.max()) ax2.set_title("Output Signal") ax3 = plt.subplot2grid((4, 6), (2, 0), rowspan = 2, colspan = 2) ax3.set_position([0.05, 0.08, 0.35, 0.35]) ax3.set_title("Frame") ax3.set_xlim(0, w.size) # ax4 = plt.subplot2grid((4, 4), (2, 1), rowspan = 2) # plt.title("Windowed") ax5 = plt.subplot2grid((4, 6), (2, 3), rowspan = 2, colspan = 4) ax5.set_position([0.47, 0.08, 0.5, 0.35]) ax5.set_title("Spectrum") ax5.set_xlabel("Frequency (Hz)") ax5.set_ylabel("Amplitude (dB)") ax5.set_xlim(0, fs/2) hN = N/2 # size of positive spectrum hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding hM2 = int(math.floor(w.size/2)) # half analysis window size by floor Ns = 512 # FFT size for synthesis (even) H = Ns/4 # Hop size used for analysis and synthesis hNs = Ns/2 pin = max(hNs, hM1) # initialize sound pointer in middle of analysis window pend = x.size - max(hNs, hM1) # last sample to start a frame fftbuffer = np.zeros(N) # initialize buffer for FFT yhw = np.zeros(Ns) # initialize output sound frame ysw = np.zeros(Ns) # initialize output sound frame yh = np.zeros(x.size) # initialize output array ys = np.zeros(x.size) # initialize output array w = w / sum(w) # normalize analysis window sw = np.zeros(Ns) ow = triang(2*H) # overlapping window sw[hNs-H:hNs+H] = ow bh = blackmanharris(Ns) # synthesis window bh = bh / sum(bh) # normalize synthesis window wr = bh # window for residual sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H] sws = H*hanning(Ns)/2 # synthesis window for stochastic lastyhloc = np.zeros(nH) # initialize synthesis harmonic locations yhphase = 2*np.pi * np.random.rand(nH) # initialize synthesis harmonic phases ax1.plot(x[:10000]) plt.draw() while pin<pend: rect = patches.Rectangle((pin-hM1, -2**7), width = w.size, height = 2**15, color = 'red', alpha = 0.3) ax1.add_patch(rect) plt.draw() rect.remove() #-----analysis----- xw = x[pin-hM1:pin+hM2] * w # window the input sound fftbuffer = np.zeros(N) # reset buffer fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer fftbuffer[N-hM2:] = xw[:hM2] X = fft(fftbuffer) # compute FFT ax3.cla() ax3.set_title("Frame") ax3.plot(x[pin-hM1:pin+hM2]) ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() ax3.set_ylim(ax3.get_ylim()) ax3.plot(w, 'r') plt.draw() ax3.cla() ax3.set_title("Windowed Frame") ax3.plot(xw, 'b') ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() ax3.cla() ax3.set_title("Windowed Frame zero-phase") ax3.plot(fftbuffer, 'b') ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() X = fft(fftbuffer) # compute FFT mX = 20 * np.log10( abs(X[:hN]) ) # magnitude spectrum of positive frequencies ploc = PP.peakDetection(mX, hN, t) pX = np.unwrap( np.angle(X[:hN]) ) # unwrapped phase spect. of positive freq. iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) # refine peak values freq = np.arange(0, fs/2, fs/N) # frequency axis in Hz freq = freq[:freq.size-1] ax5.cla() ax5.set_title("Spectrum") ax5.set_xlabel("Frequency (Hz)") ax5.set_ylabel("Amplitude (dB)") ax5.set_xlim(0, fs/2) ax5.plot(freq, mX, 'b') ax5.set_ylim(ax5.get_ylim()) ax5.fill_between(freq, ax5.get_ylim()[0], mX, facecolor = 'blue', alpha = 0.3) plt.draw() ax5.plot(np.float32(iploc)/N*fs, ipmag, 'ro', ms = 4, alpha = 0.4) plt.draw() f0 = fd.f0DetectionTwm(iploc, ipmag, N, fs, f0et, minf0, maxf0) # find f0 if f0 > 0: loc = np.where(iploc/N*fs == f0)[0] if loc.size == 0: loc = np.argmin(np.abs(iploc/N*fs-f0)) # closest peak location ax5.plot(f0, ipmag[loc], 'go', ms = 4, alpha = 1) plt.draw() hloc = np.zeros(nH) # initialize harmonic locations hmag = np.zeros(nH)-100 # initialize harmonic magnitudes hphase = np.zeros(nH) # initialize harmonic phases hf = (f0>0)*(f0*np.arange(1, nH+1)) # initialize harmonic frequencies hi = 0 # initialize harmonic index npeaks = ploc.size # number of peaks found while f0>0 and hi<nH and hf[hi]<fs/2 : # find harmonic peaks dev = min(abs(iploc/N*fs - hf[hi])) pei = np.argmin(abs(iploc/N*fs - hf[hi])) # closest peak if ( hi==0 or not any(hloc[:hi]==iploc[pei]) ) and dev<maxhd*hf[hi] : hloc[hi] = iploc[pei] # harmonic locations hmag[hi] = ipmag[pei] # harmonic magnitudes hphase[hi] = ipphase[pei] # harmonic phases hi += 1 # increase harmonic index ax5.plot(np.float32(hloc)/N*fs, hmag, 'yo', ms = 4, alpha = 0.7) plt.draw() hloc = (hloc!=0) * (hloc*Ns/N) # synth. locs ri = pin-hNs-1 # input sound pointer for residual analysis xw2 = x[ri:ri+Ns]*wr # window the input sound fftbuffer = np.zeros(Ns) # reset buffer fftbuffer[:hNs] = xw2[hNs:] # zero-phase window in fftbuffer fftbuffer[hNs:] = xw2[:hNs] X2 = fft(fftbuffer) # compute FFT for residual analysis #-----synthesis----- Yh = GS.genSpecSines(hloc, hmag, hphase, Ns) # generate spec sines Xr = X2-Yh # get the residual complex spectrum mXr = 20 * np.log10( abs(Xr[:hNs]) ) # magnitude spectrum of residual mXrenv = resample(np.maximum(-200, mXr), mXr.size*stocf) # decimate the magnitude spectrum mYs = resample(mXrenv, hNs) # interpolate to original size pYs = 2*np.pi*np.random.rand(hNs) # generate phase random values Ys = np.zeros(Ns, dtype = complex) Ys[:hNs] = 10**(mYs/20) * np.exp(1j*pYs) # generate positive freq. Ys[hNs+1:] = 10**(mYs[:0:-1]/20) * np.exp(-1j*pYs[:0:-1]) # generate negative freq. fftbuffer = np.zeros(Ns) fftbuffer = np.real( ifft(Yh) ) # inverse FFT ax3.cla() ax3.set_title("Reconstructed Frame") ax3.plot(fftbuffer, 'g') ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() yhw[:hNs-1] = fftbuffer[hNs+1:] # undo zero-phase window yhw[hNs-1:] = fftbuffer[:hNs+1] ax3.cla() ax3.set_title("Reconstructed Frame") ax3.plot(yhw, 'g') ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() fftbuffer = np.zeros(Ns) fftbuffer = np.real( ifft(Ys) ) ysw[:hNs-1] = fftbuffer[hNs+1:] # residual in time domain using inverse FFT ysw[hNs-1:] = fftbuffer[:hNs+1] yh[ri:ri+Ns] += sw*yhw # overlap-add for sines ys[ri:ri+Ns] += sws*ysw # overlap-add for stochastic pin += H # advance sound pointer ax3.cla() ax3.set_title("Reconstructed Frame") ax3.plot(sw*yhw, 'g') ax3.set_xlim(0, w.size) ax3.ticklabel_format(scilimits = (-3,3)) # use scientific limits above 1e3 plt.draw() rect2 = patches.Rectangle((pin-hM1, -2**7), width = Ns, height = 2**15, color = 'green', alpha = 0.3) ax2.cla() ax2.set_xlim(0, 10000) ax2.set_ylim(x.min(), x.max()) ax2.set_title("Output Signal") ax2.add_patch(rect2) ax2.plot(yh, 'b') plt.draw() rect2.remove() y = yh+ys return y, yh, ys
def main(argv=sys.argv): #Earth's parameters #~ beta = 4.e3 #m/s #~ rho = 3.e3 #kg/m^3 #~ mu = rho*beta*beta PLotSt = ["IU.TRQA.00.LHZ", "IU.LVC.00.LHZ", "II.NNA.00.LHZ", "IU.RAR.00.LHZ"] #PlotSubf = [143, 133, 123, 113, 103, 93, # 83, 73, 63, 53] PlotSubf = [6,3] #Set rup_vel = 0 to have a point source solution RupVel = 2.1 #Chilean eq from Lay et al t_h = 10. # Half duration for each sf noiselevel = 0.0# L1 norm level of noise mu =40e9 #W-Phase filter corners = 4. fmin = 0.001 fmax = 0.005 ### Data from Chilean 2010 EQ (Same as W phase inv.) strike = 18. dip = 18. rake = 104. # 109. rakeA = rake + 45. rakeB = rake - 45. ### Fault's grid parameters nsx = 21 #Number of sf along strike nsy = 11 #Number of sf along dip flen = 600. #Fault's longitude [km] along strike fwid = 300. #Fault's longitude [km] along dip direc = 0 #Directivity 0 = bilateral Min_h = 10. #Min depth of the fault ### Derivated parameters: nsf = nsx*nsy sflen = flen/float(nsx) sfwid = fwid/float(nsy) swp = [1, 0, 2] # useful to swap (lat,lon, depth) mindist = flen*fwid # minimun dist to the hypcen (initializing) ###Chessboard #weight = np.load("RealSol.npy") weight = np.zeros(nsf) weight[::2] = 1 #weight[::2] = 1 #~ weight[10]=15 #~ weight[5001]=10 #~ weight[3201]=2 ## Setting dirs and reading files. GFdir = "/home/roberto/data/GFS/" workdir = os.path.abspath(".")+"/" datadir = workdir + "DATA/" tracesfilename = workdir + "goodtraces.dat" tracesdir = workdir + "WPtraces/" try: reqfilename = glob.glob(workdir + '*.syn.req')[0] except IndexError: print "There is not *.syn.req file in the dir" sys.exit() basename = reqfilename.split("/")[-1][:-4] if not os.path.exists(tracesfilename): print tracesfilename, "does not exist." exit() if not os.path.exists(datadir): os.makedirs(datadir) if not os.path.exists(tracesdir): os.makedirs(tracesdir) tracesfile = open(tracesfilename) reqfile = open(reqfilename) trlist = readtraces(tracesfile) eqdata = readreq(reqfile) tracesfile.close() reqfile.close() ####Hypocentre from ### http://earthquake.usgs.gov/earthquakes/eqinthenews/2010/us2010tfan/ cmteplat = -35.91#-35.85#-36.03#-35.83 cmteplon = -72.73#-72.72#-72.83# -72.67 cmtepdepth= 35. eq_hyp = (cmteplat,cmteplon,cmtepdepth) ############ # Defining the sf system grid, sblt = fault_grid('CL-2010',cmteplat,cmteplon, cmtepdepth, direc, Min_h, strike, dip, rake, flen,fwid ,nsx,nsy, Verbose=False,ffi_io=True,gmt_io=True) print ('CL-2010',cmteplat,cmteplon, cmtepdepth, direc, Min_h, strike, dip, rake, flen,fwid ,nsx,nsy) print grid[0][1] #sys.exit() #This calculation is inside of the loop #~ NP = [strike, dip, rake] #~ M = np.array(NodalPlanetoMT(NP)) #~ Mp = np.sum(M**2)/np.sqrt(2) ############################################################################# ######Determining the sf closest to the hypocentre: min_Dist_hyp_subf = flen *fwid for subf in range(nsf): sblat = grid[subf][1] sblon = grid[subf][0] sbdepth = grid[subf][2] sf_hyp = (sblat,sblon, sbdepth) Dist_hyp_subf = hypo2dist(eq_hyp,sf_hyp) if Dist_hyp_subf < min_Dist_hyp_subf: min_Dist_hyp_subf = Dist_hyp_subf min_sb_hyp = sf_hyp hyp_subf = subf ####Determining trimming times: test_tr = read(GFdir + "H003.5/PP/GF.0001.SY.LHZ.SAC")[0] t0 = test_tr.stats.starttime TrimmingTimes = {} # Min. Distace from the fault to each station. A =0 for trid in trlist: metafile = workdir + "DATA/" + "META." + trid + ".xml" META = DU.getMetadataFromXML(metafile)[trid] stlat = META['latitude'] stlon = META['longitude'] dist = locations2degrees(min_sb_hyp[0],min_sb_hyp[1],\ stlat,stlon) parrivaltime = getTravelTimes(dist,min_sb_hyp[2])[0]['time'] ta = t0 + parrivaltime tb = ta + round(15.*dist) TrimmingTimes[trid] = (ta, tb) ########################### DIST = [] # Ordering the stations in terms of distance for trid in trlist: metafile = workdir + "DATA/" + "META." + trid + ".xml" META = DU.getMetadataFromXML(metafile)[trid] lat = META['latitude'] lon = META['longitude'] trdist = locations2degrees(cmteplat, cmteplon,lat,lon) DIST.append(trdist) DistIndex = lstargsort(DIST) trlist = [trlist[i] for i in DistIndex] stdistribution = StDistandAzi(trlist, eq_hyp , workdir + "DATA/") StDistributionPlot(stdistribution) #exit() #Main loop for subf in range(nsf): print subf sflat = grid[subf][1] sflon = grid[subf][0] sfdepth = grid[subf][2] #~ strike = grid[subf][3] #+ 360. #~ dip = grid[subf][4] #~ rake = grid[subf][5] # NP = [strike, dip, rake] NPA = [strike, dip, rakeA] NPB = [strike, dip, rakeB] M = np.array(NodalPlanetoMT(NP)) MA = np.array(NodalPlanetoMT(NPA)) MB = np.array(NodalPlanetoMT(NPB)) #Time delay is calculated as the time in which #the rupture reach the subfault sf_hyp = (sflat, sflon, sfdepth) Dist_ep_subf = hypo2dist(eq_hyp,sf_hyp) if Dist_ep_subf < mindist: mindist = Dist_ep_subf minsubf = subf if RupVel == 0: t_d = eqdata['time_shift'] else: t_d = round(Dist_ep_subf/RupVel) #-59. print sflat, sflon, sfdepth # Looking for the best depth dir: depth = [] depthdir = [] for file in os.listdir(GFdir): if file[-2:] == ".5": depthdir.append(file) depth.append(float(file[1:-2])) BestDirIndex = np.argsort(abs(sfdepth\ - np.array(depth)))[0] hdir = GFdir + depthdir[BestDirIndex] + "/" ### SYN = np.array([]) SYNA = np.array([]) SYNB = np.array([]) for trid in trlist: metafile = workdir + "DATA/" + "META." + trid + ".xml" META = DU.getMetadataFromXML(metafile)[trid] lat = META['latitude'] lon = META['longitude'] #Subfault loop #GFs Selection: ##Change to folloing loop dist = locations2degrees(sflat,sflon,lat,lon) azi = -np.pi/180.*gps2DistAzimuth(lat,lon, sflat,sflon)[2] trPPsy, trRRsy, trRTsy, trTTsy = \ GFSelectZ(hdir,dist) trROT = MTrotationZ(azi, trPPsy, trRRsy, trRTsy, trTTsy) orig = trROT[0].stats.starttime dt = trROT[0].stats.delta trianglen = 2.*int(t_h/dt)-1. FirstValid = int(trianglen/2.) + 1 # to delete window = triang(trianglen) window /= np.sum(window) #window = np.array([1.]) parrivaltime = getTravelTimes(dist,sfdepth)[0]['time'] t1 = TrimmingTimes[trid][0] - t_d t2 = TrimmingTimes[trid][1] - t_d for trR in trROT: trR.data *= 10.**-21 ## To get M in Nm trR.data -= trR.data[0] AUX1 = len(trR) trR.data = convolve(trR.data,window,mode='valid') AUX2 = len(trR) mean = np.mean(np.hstack((trR.data[0]*np.ones(FirstValid),\ trR.data[:60./trR.stats.delta*1.-FirstValid+1]))) #mean = np.mean(trR.data[:60]) trR.data -= mean trR.data = bp.bandpassfilter(trR.data,len(trR), trR.stats.delta,\ corners , 1 , fmin, fmax) t_l = dt*0.5*(AUX1 - AUX2) trR.trim(t1-t_l,t2-t_l, pad=True, fill_value=trR.data[0]) #We lost t_h due to the convolution #~ for trR in trROT: #~ trR.data *= 10.**-23 ## To get M in Nm #~ trR.data -= trR.data[0] #~ trR.data = convolve(trR.data,window,mode='same') #~ #mean = np.mean(np.hstack((trR.data[0]*np.ones(FirstValid),\ #~ #trR.data[:60./trR.stats.delta*1.-FirstValid+1]))) #~ mean = np.mean(trR.data[:60]) #~ trR.data -= mean #~ trR.data = bp.bandpassfilter(trR.data,len(trR), trR.stats.delta,\ #~ corners , 1 , fmin, fmax) #~ trR.trim(t1,t2,pad=True, fill_value=trR.data[0]) trROT = np.array(trROT) syn = np.dot(trROT.T,M) synA = np.dot(trROT.T,MA) synB = np.dot(trROT.T,MB) SYN = np.append(SYN,syn) SYNA = np.append(SYNA,synA) SYNB = np.append(SYNB,synB) print np.shape(A), np.shape(np.array([SYN])) if subf == 0: A = np.array([SYN]) AA = np.array([SYNA]) AB = np.array([SYNB]) else: A = np.append(A,np.array([SYN]),0) AA = np.append(AA,np.array([SYNA]),0) AB = np.append(AB,np.array([SYNB]),0) AC = np.vstack((AA,AB)) print np.shape(AC) print np.shape(weight) B = np.dot(A.T,weight) stsyn = Stream() n = 0 Ntraces= {} for trid in trlist: spid = trid.split(".") print trid NMIN = 1. + (TrimmingTimes[trid][1] - TrimmingTimes[trid][0]) / dt Ntraces[trid] = (n,NMIN + n) trsyn = Trace(B[n:NMIN+n]) n += NMIN trsyn.stats.network = spid[0] trsyn.stats.station = spid[1] trsyn.stats.location = spid[2] trsyn.stats.channel = spid[3] trsyn = AddNoise(trsyn,level = noiselevel) #trsyn.stats.starttime = stsyn.append(trsyn) stsyn.write(workdir+"WPtraces/" + basename + ".decov.trim.mseed", format="MSEED") ##################################################### # Plotting: ##################################################### #we are going to reflect the y axis later, so: print minsubf hypsbloc = [minsubf / nsy , -(minsubf % nsy) - 2] #Creating the strike and dip axis: StrikeAx= np.linspace(0,flen,nsx+1) DipAx= np.linspace(0,fwid,nsy+1) DepthAx = DipAx*np.sin(np.pi/180.*dip) + Min_h hlstrike = StrikeAx[hypsbloc[0]] + sflen*0.5 hldip = DipAx[hypsbloc[1]] + sfwid*0.5 hldepth = DepthAx[hypsbloc[1]] + sfwid*0.5*np.sin(np.pi/180.*dip) StrikeAx = StrikeAx - hlstrike DipAx = DipAx - hldip XX, YY = np.meshgrid(StrikeAx, DepthAx) XX, ZZ = np.meshgrid(StrikeAx, DipAx ) sbarea = sflen*sfwid SLIPS = weight.reshape(nsx,nsy).T#[::-1,:] SLIPS /= mu*1.e6*sbarea ######Plot:##################### plt.figure() ax = host_subplot(111) im = ax.pcolor(XX, YY, SLIPS, cmap="jet") ax.set_ylabel('Depth [km]') ax.set_ylim(DepthAx[-1],DepthAx[0]) # Creating a twin plot ax2 = ax.twinx() #im2 = ax2.pcolor(XX, ZZ, SLIPS[::-1,:], cmap="Greys") im2 = ax2.pcolor(XX, ZZ, SLIPS[::-1,:], cmap="jet") ax2.set_ylabel('Distance along the dip [km]') ax2.set_xlabel('Distance along the strike [km]') ax2.set_ylim(DipAx[0],DipAx[-1]) ax2.set_xlim(StrikeAx[0],StrikeAx[-1]) ax.axis["bottom"].major_ticklabels.set_visible(False) ax2.axis["bottom"].major_ticklabels.set_visible(False) ax2.axis["top"].set_visible(True) ax2.axis["top"].label.set_visible(True) divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad=0.1) cb = plt.colorbar(im, cax=cax, orientation="horizontal") cb.set_label("Slip [m]") ax2.plot([0], [0], '*', ms=225./(nsy+4)) ax2.set_xticks(ax2.get_xticks()[1:-1]) #ax.set_yticks(ax.get_yticks()[1:]) #ax2.set_yticks(ax2.get_yticks()[:-1]) #########Plotting the selected traces: nsp = len(PLotSt) * len(PlotSubf) plt.figure(figsize=(13,11)) plt.title("Synthetics for rake = " + str(round(rake))) mindis = [] maxdis = [] for i, trid in enumerate(PLotSt): x = np.arange(0,Ntraces[trid][1]-Ntraces[trid][0], dt) for j, subf in enumerate(PlotSubf): y = A[subf, Ntraces[trid][0]:Ntraces[trid][1]] if j == 0: yy = y else: yy = np.vstack((yy,y)) maxdis.append(np.max(yy)) mindis.append(np.min(yy)) for i, trid in enumerate(PLotSt): x = np.arange(0,Ntraces[trid][1]-Ntraces[trid][0], dt) for j, subf in enumerate(PlotSubf): y = A[subf, Ntraces[trid][0]:Ntraces[trid][1]] plt.subplot2grid((len(PlotSubf), len(PLotSt)), (j, i)) plt.plot(x,y, linewidth=2.5) if j == 0: plt.title(trid) fig = plt.gca() fig.axes.get_yaxis().set_ticks([]) fig.set_ylabel(str(subf),rotation=0) fig.set_xlim((x[0],x[-1])) fig.set_ylim((mindis[i],maxdis[i])) if subf != PlotSubf[-1]: fig.axes.get_xaxis().set_ticks([]) plt.show()