def test_padded_align_odd() -> None: """ Test the padded cross-correlation method with two gaussian pulses of odd length. """ # make some time arrays and define a time delta t = np.linspace(-2 * np.pi, 2 * np.pi, 100) dt = 3.675 * (t[1] - t[0]) t = np.linspace(-1, 1, 199, endpoint=False) # construct two identical gaussian pulses x = np.real(signal.gausspulse(t, fc=5)) y = np.real(signal.gausspulse(t + dt, fc=5)) # compute the delay without any upsampling d = align.xcorr_delay(x, y, 30) # and apply the delay y = align.apply_delay(y, d) # and test the top-level call ynew = align.align(x, y, method="xcorr", factor=30) # and check that the alignment is within a certain known accuracy assert np.std(np.abs(x - y)) < 0.005 assert np.std(np.abs(y - ynew)) < 5e-5
def test_fft_align() -> None: """ Test FFT phase shift alignment """ for N in [178, 179, 200, 201]: # make some time arrays and define a time delta t = np.linspace(-2 * np.pi, 2 * np.pi, N // 2) dt = 3.675 * (t[1] - t[0]) t = np.linspace(-1, 1, N, endpoint=False) true = dt / (t[1] - t[0]) # construct two identical gaussian pulses x = np.real(signal.gausspulse(t, fc=5)) y = np.real(signal.gausspulse(t + dt, fc=5)) # compute the delay with upsampling delay = align.fft_delay(x, y) # and apply the delay y = align.apply_delay(y, delay) # use the top-level call ynew = align.align(x, y, method="fft") # and check that the alignment is within a certain known accuracy assert np.abs(true - delay) < 1e-3 assert np.mean(np.abs(x - y)) < 1e-3 assert np.mean(np.abs(x - ynew)) < 2e-4 assert np.mean(np.abs(y - ynew)) < 3e-5
def test_gauss_align() -> None: """ Test Gaussian interpolation of unpadded cross correlation. """ # make some time arrays and define a time delta t = np.linspace(-2 * np.pi, 2 * np.pi, 100) dt = 3.675 * (t[1] - t[0]) t = np.linspace(-1, 1, 200, endpoint=False) # construct two identical gaussian pulses x = np.real(signal.gausspulse(t, fc=5)) y = np.real(signal.gausspulse(t + dt, fc=5)) # compute the delay with upsampling d_padded = align.xcorr_delay(x, y, 30) # compute the delay without any upsampling d = align.xcorr_delay(x, y, fit="gauss") # compute the new signal y = align.apply_delay(y, d) # and test the top-level call ynew = align.align(x, y, method="xcorr", factor=30) # and check that the alignment is within a certain known accuracy assert np.abs(d - d_padded) < 0.05 assert np.mean(np.abs(x - y)) < 7e-4 assert np.mean(np.abs(x - ynew)) < 7e-4 assert np.mean(np.abs(y - ynew)) < 5e-5
def test_correlate(self): # create noise and a glitch template at 1000 Hz noise = self.TEST_CLASS(numpy.random.normal(size=16384 * 64), sample_rate=16384, epoch=-32).zpk([], [1], 1) glitchtime = -16.5 glitch = self.TEST_CLASS(signal.gausspulse(numpy.arange( -1, 1, 1. / 16384), bw=100), sample_rate=16384, epoch=glitchtime - 1) # check that, without a signal present, we only see background snr = noise.correlate(glitch, whiten=True) tmax = snr.times[snr.argmax()] assert snr.size == noise.size assert not numpy.isclose(tmax.value, glitchtime) nptest.assert_almost_equal(snr.mean().value, 0.0, decimal=1) nptest.assert_almost_equal(snr.std().value, 1.0, decimal=1) # inject and recover the glitch data = noise.inject(glitch * 1e-4) snr = data.correlate(glitch, whiten=True) tmax = snr.times[snr.argmax()] nptest.assert_almost_equal(tmax.value, glitchtime)
def test_gate(self): # generate Gaussian noise with std = 0.5 noise = self.TEST_CLASS(numpy.random.normal(scale=0.5, size=16384*64), sample_rate=16384, epoch=-32) # generate a glitch with amplitude 20 at 1000 Hz glitchtime = 0.0 glitch = signal.gausspulse(noise.times.value - glitchtime, bw=100) * 20 data = noise + glitch # check that the glitch is at glitchtime as expected tmax = data.times.value[data.argmax()] nptest.assert_almost_equal(tmax, glitchtime) # gating method will be called with whiten = False to decouple # whitening method from gating method tzero = 1.0 tpad = 1.0 threshold = 10.0 gated = data.gate(tzero=tzero, tpad=tpad, threshold=threshold, whiten=False) # check that the maximum value is not within the region set to zero tleft = glitchtime - tzero tright = glitchtime + tzero assert not tleft < gated.times.value[gated.argmax()] < tright # check that there are no remaining values above the threshold assert gated.max() < threshold
def test_gate(self): # generate Gaussian noise with std = 0.5 noise = self.TEST_CLASS(numpy.random.normal(scale=0.5, size=16384 * 64), sample_rate=16384, epoch=-32) # generate a glitch with amplitude 20 at 1000 Hz glitchtime = 0.0 glitch = signal.gausspulse(noise.times.value - glitchtime, bw=100) * 20 data = noise + glitch # check that the glitch is at glitchtime as expected tmax = data.times.value[data.argmax()] nptest.assert_almost_equal(tmax, glitchtime) # gating method will be called with whiten = False to decouple # whitening method from gating method tzero = 1.0 tpad = 1.0 threshold = 10.0 gated = data.gate(tzero=tzero, tpad=tpad, threshold=threshold, whiten=False) # check that the maximum value is not within the region set to zero tleft = glitchtime - tzero tright = glitchtime + tzero assert not tleft < gated.times.value[gated.argmax()] < tright # check that there are no remaining values above the threshold assert gated.max() < threshold
def cwt_scipy(): st = obspy.read()[0].data t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) print(np.shape(st), st.dtype) print(np.shape(sig), sig.dtype) widths = np.arange(1, 100) cwtmatr = abs(signal.cwt(st, signal.morlet2, widths)) # t = np.linspace(0, dt * npts, npts) # x, y = np.meshgrid(t, np.logspace(np.log10(1), np.log10(50), cwtmatr.shape[0])) # print(np.shape(y)) # plt.pcolormesh(x, y, np.abs(cwtmatr), cmap=obspy_sequential) # plt.yscale('log') plt.imshow(cwtmatr, aspect='auto') # plt.imshow(cwtmatr, extent=[-1, 1, 1, 30], cmap='PRGn', aspect='auto', # vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) plt.savefig('cwt_scipy.png') plt.close()
def main(): t = np.linspace(-1, 1, 100) def f(t): return np.sin( np.pi * t) + 0.1 * np.cos(7 * np.pi * t + 0.3) + 0.2 * np.cos( 24 * np.pi * t) + 0.3 * np.cos(12 * np.pi * t + 0.5) fig, axes = plt.subplots(1, 3, figsize=(12, 3)) axes[0].plot(t, signal.gausspulse(t, fc=5, bw=0.5)) axes[0].set_title("gausspulse") t *= 5 * np.pi axes[1].plot(t, signal.sawtooth(t)) axes[1].set_title("chirp") axes[2].plot(t, signal.square(t)) axes[2].set_title("gausspulse") t = np.linspace(0, 4, 400) plt.plot(t, f(t)) # 中值滤波函数 plt.plot(t, signal.medfilt(f(t), kernel_size=55), linewidth=2, label="medfilt") # 维纳滤波函数 plt.plot(t, signal.wiener(f(t), mysize=55), linewidth=2, label="wiener") plt.legend() plt.show()
def test_whiten(self): # create noise with a glitch in it at 1000 Hz noise = self.TEST_CLASS(numpy.random.normal(loc=1, scale=.5, size=16384 * 64), sample_rate=16384, epoch=-32).zpk([], [0], 1) glitchtime = 0.5 glitch = signal.gausspulse(noise.times.value - glitchtime, bw=100) * 1e-4 data = noise + glitch # when the input is stationary Gaussian noise, the output should have # zero mean and unit variance whitened = noise.whiten(detrend='linear') assert whitened.size == noise.size nptest.assert_almost_equal(whitened.mean().value, 0.0, decimal=2) nptest.assert_almost_equal(whitened.std().value, 1.0, decimal=2) # when a loud signal is present, the max amplitude should be recovered # at the time of that signal tmax = data.times[data.argmax()] assert not numpy.isclose(tmax.value, glitchtime) whitened = data.whiten(detrend='linear') tmax = whitened.times[whitened.argmax()] nptest.assert_almost_equal(tmax.value, glitchtime)
def gen_samples(self, time, seq_shape, kwargs): # TODO: MAKE IT DEPENDENT OF PARAMETERS, SAMPLE OUTSIDE if seq_shape == "constant": samples = np.ones(shape=time.shape) * kwargs["amp"] params = np.array([ kwargs["amp"], ]) return samples, params elif seq_shape in ["sinusoidal", "square", "sawtooth"]: samples = 0 if seq_shape == "sinusoidal": samples = np.sin(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] elif seq_shape == "square": samples = ss.square(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] elif seq_shape == "sawtooth": samples = ss.sawtooth(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] params = np.array([kwargs["amp"], kwargs["freq"], kwargs["phase"]]) return samples, params elif seq_shape == "gaussian_pulses": amp = np.random.uniform(low=self.amp_range[0], high=self.amp_range[1]) freq = np.random.uniform(low=self.freq_range[0], high=self.freq_range[1]) pulse_width = np.random.uniform(low=self.pulse_width_range[0], high=self.pulse_width_range[1]) params = np.array([0]) samples = ss.gausspulse(time, freq, pulse_width)
def test_whiten(self): # create noise with a glitch in it at 1000 Hz noise = self.TEST_CLASS( numpy.random.normal(loc=1, scale=.5, size=16384 * 64), sample_rate=16384, epoch=-32).zpk([], [0], 1) glitchtime = 0.5 glitch = signal.gausspulse(noise.times.value - glitchtime, bw=100) * 1e-4 data = noise + glitch # when the input is stationary Gaussian noise, the output should have # zero mean and unit variance whitened = noise.whiten(detrend='linear') assert whitened.size == noise.size nptest.assert_almost_equal(whitened.mean().value, 0.0, decimal=2) nptest.assert_almost_equal(whitened.std().value, 1.0, decimal=2) # when a loud signal is present, the max amplitude should be recovered # at the time of that signal tmax = data.times[data.argmax()] assert not numpy.isclose(tmax.value, glitchtime) whitened = data.whiten(detrend='linear') tmax = whitened.times[whitened.argmax()] nptest.assert_almost_equal(tmax.value, glitchtime)
def make_noise(text_length, filename): # checking audio file to match with nb_samples = audiofile.samples(filename) sampling_rate = audiofile.sampling_rate(filename) # in Hz # Generate random logarithmic noise noise = np.random.lognormal(0, 1, nb_samples) noise /= np.amax(np.abs(noise)) # Filter with bandpass filter nyq = 0.5 * sampling_rate low = text_length / nyq high = (50 + text_length) / nyq order = 1 b, a = signal.butter(order, [low, high], btype="band") filtered_noise = signal.lfilter(b, a, noise) # create Gaussian enveloppe t = np.linspace(start=-0.5, stop=0.5, num=nb_samples, endpoint=False) i, e = signal.gausspulse(t, fc=5, retenv=True, bwr=-6.0) out_signal = np.multiply(filtered_noise, e) out_signal *= 30 # write audio file audiofile.write(filename + ".noise.wav", out_signal, sampling_rate) print("text length was :", text_length)
def feedforward_modelbased(delay): t = np.linspace(-1, 1, in_len, endpoint=False) i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True) temp = np.zeros((1, in_len)) temp[0, :] = i out = np.zeros((1, in_len)) LEN = int(delay.shape[1] / 2) for i in range(LEN): scale = delay[0][LEN + i] - 0.5 # Add scale noise scale += 1e-7 * np.random.randn() # Add delay and scaling delay_scaled = scale * np.roll(temp, int( (in_len * delay).round()[0][i])) # Add exponential damping delay_scaled = np.multiply( delay_scaled, 100.0 * delay[0][-1] / np.linspace(1, in_len, in_len, endpoint=True)) # Add all delayed scaled pulses together out += delay_scaled # Adding noise out += 1e-5 * np.random.randn(1, in_len) return out
def test_save_loudest_tile_features(): # prepare input data channel = GW.channels[0] noise = TimeSeries(numpy.random.normal(loc=1, scale=.5, size=16384 * 68), sample_rate=16384, epoch=-34).zpk([], [0], 1) glitch = TimeSeries(signal.gausspulse(numpy.arange(-1, 1, 1. / 16384), bw=100), sample_rate=16384, epoch=-1) * 1e-4 in_ = noise.inject(glitch) _, _, _, qgram, _, _, _ = core.scan(gps=0, channel=channel, xoft=in_, resample=4096, fftlength=8) # test loudest tiles channel.save_loudest_tile_features(qgram, correlate=glitch) assert channel.Q == numpy.around(qgram.plane.q, 1) assert channel.energy == numpy.around(qgram.peak['energy'], 1) assert channel.snr == numpy.around(qgram.peak['snr'], 1) assert channel.t == numpy.around(qgram.peak['time'], 3) assert channel.f == numpy.around(qgram.peak['frequency'], 1) assert channel.corr == numpy.around(glitch.max().value, 1) assert channel.delay == 0.0 assert channel.stdev == glitch.std().value
def plotGpulse(self, amp, freq): self.amp = amp self.freq = freq self.Fs: int = 44100 self.x = arange(0, 1, 1 / self.Fs) self.y = (amp / 10) * gausspulse((self.x, freq)) self.fullPlot.plot(self.x, self.y, pen=self.penR) self.zoomedPlot.plot(self.x, self.y, pen=self.penB)
def wavelet(): t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) widths = np.arange(1, 31) cwtmatr = signal.cwt(sig, signal.ricker, widths) plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto', vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) plt.show() return
def generate_SineGaussianBlip(fc, bw, duration): #returns sine gaussian blip with bandwidth = bw, centre frequency = fc t = np.linspace(-duration/2, duration/2, duration*4096) sine_gaussian = signal.gausspulse(t, fc=fc, bw=bw) waveform = TimeSeries(sine_gaussian, delta_t=1/4096) return waveform
def test_gausspulse(self, time_data_gen, num_samps, fc): cpu_time, gpu_time = time_data_gen(0, 10, num_samps) cpu_pwm = signal.gausspulse(cpu_time, fc, retquad=True, retenv=True) gpu_pwm = cp.asnumpy( cusignal.gausspulse(gpu_time, fc, retquad=True, retenv=True)) assert array_equal(cpu_pwm, gpu_pwm)
def test_gausspulse(num_samps, fc): cpu_time = np.linspace(0, 10, num_samps) gpu_time = cp.asarray(cpu_time) cpu_pwm = signal.gausspulse(cpu_time, fc, retquad=True, retenv=True) gpu_pwm = cp.asnumpy( cusignal.gausspulse(gpu_time, fc, retquad=True, retenv=True)) assert array_equal(cpu_pwm, gpu_pwm)
def set_gaussian_excitation (self, plot=False, bw=.5, bwr=-6, num_sigmas=3): '''Define the ultrasound excitation signal. `bw` is the fractional bandwidth (between 0 and 1) of the Gaussian modulating signal relative to `tx.center_frequency. `bwr` is the reference level at which the fractional bandwidth is calculated (dB). (See scipy.signal.gausspulse.) `num_sigmas` is how many standard deviations outwards from the center to sample in either direction.''' from scipy.signal import gausspulse import matplotlib.pyplot as plt fc = self.tx.center_frequency fs = self.sampling_frequency # https://github.com/scipy/scipy/blob/14142ff70d84a6ce74044a27919c850e893648f7/scipy/signal/waveforms.py#L232 # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f) bwr = -6 ref = pow (10.0, bwr / 20.0) a = -(np.pi * fc * bw) ** 2 / (4.0 * np.log (ref)) time_sigma = 1 / np.sqrt (2 * a) time = np.arange (-num_sigmas * time_sigma, num_sigmas * time_sigma, 1 / fs) if plot: # Plot the excitation signal excitation, envelope = gausspulse( time, fc=fc, bw=bw, bwr=bwr, retenv=True) plt.plot(envelope, 'g--', excitation) plt.title ('Excitation Signal', fontsize=20, pad=20) plt.xlabel (r'Time [$\mu$s]', fontsize=14, labelpad=10) plt.gca ().set_facecolor ('white') xticks = plt.xticks ()[0] plt.gca ().set_xticklabels ([f'{i*1e6/fs:.2f}' for i in xticks]) plt.grid (False, axis='y') plt.grid (True, axis='x', linestyle=':', color='gray') plt.yticks ([]) plt.show () else: excitation = gausspulse(time, fc=fc, bw=bw, bwr=bwr) # Set the excitation signal self.excitation = self.new_tensor (excitation)
def create_gaussian_pulse(center_freq, samp_freq, bandwidth=2/3, bwr=-6, tpr=-60, baseband=False, viz=False): """ Modification to `scipy.signal.gausspulse`: https://github.com/scipy/scipy/blob/v0.14.0/scipy/signal/waveforms.py#L161 Their version doesn't let you set a center frequency of 0 (baseband case). :return: """ # compute within [+/- cutoff] t_cutoff = gausspulse('cutoff', fc=center_freq, bw=bandwidth, bwr=bwr, tpr=tpr) # gaussian coeff (Time domain compressive beam forming of ultrasound signals, David) denom = 2 * np.pi * bandwidth * center_freq tv = -(8 * np.log(10 ** (bwr / 20)) / (denom * denom)) alpha = 1. / 2 / tv # compute pulse t_vals = np.arange(-1. * t_cutoff, t_cutoff, 1 / samp_freq) pulse = np.exp(-alpha * t_vals * t_vals) if not baseband: pulse *= np.cos(2 * np.pi * center_freq * t_vals) if viz: f, (ax1, ax2) = plt.subplots(2,1) ax1.set_title("Gaussian pulse") ax1.plot(t_vals, pulse) ax1.grid() ax1.autoscale(enable=True, axis='x', tight=True) ax1.set_xlabel("Time [s]") # ax1.get_xaxis().set_ticklabels([]) if baseband: f_vals = np.linspace(-center_freq, center_freq, num=1000) H = gauss_ft(f_vals, alpha) ax2.plot(f_vals, 20*np.log10(np.abs(H))) else: f_vals = np.linspace(-2*center_freq, 2*center_freq, num=1000) H = gauss_ft(f_vals, alpha, fc=center_freq) ax2.plot(f_vals, 20*np.log10(np.abs(H)), label="pulse") ax2.axvline(x=center_freq, c='r', label="center frequency") ax2.legend() ax2.grid() ax2.set_xlabel("Frequency [Hz]") ax2.autoscale(enable=True, axis='x', tight=True) ax2.set_ylabel("dB") return pulse, t_vals, alpha
def test_poly_align() -> None: """ Test polynomial interpolation of unpadded cross correlation. """ # make some time arrays and define a time delta t = np.linspace(-2 * np.pi, 2 * np.pi, 100) dt = 3.675 * (t[1] - t[0]) t = np.linspace(-1, 1, 200, endpoint=False) # construct two identical gaussian pulses x = np.real(signal.gausspulse(t, fc=5)) y = np.real(signal.gausspulse(t + dt, fc=5)) # compute the delay with upsampling d_padded = align.xcorr_delay(x, y, 30) # compute the delay without any upsampling d = align.xcorr_delay(x, y, fit="poly") # and check that the alignment is within a certain known accuracy assert np.abs(d - d_padded) < 0.05
def test_simple_align() -> None: """ Test the basic cross-correlation method with two gaussian pulses. """ # make some time arrays and define a time delta t = np.linspace(-2 * np.pi, 2 * np.pi, 100) dt = 3.675 * (t[1] - t[0]) t = np.linspace(-1, 1, 2 * 100, endpoint=False) # construct two identical gaussian pulses x = np.real(signal.gausspulse(t, fc=5)) y = np.real(signal.gausspulse(t + dt, fc=5)) # compute the delay without any upsampling d = align.xcorr_delay(x, y) # and apply the delay y = align.apply_delay(y, d) # and check that the alignment is within a certain accuracy assert np.std(x - y) < 0.06
def run(self, time, frq, bw=0.5, bwr=-6, ampl=1, retquad=False): """ Method to generate a sine signal for a given time array, a frequency and amplitude. """ if retquad is False: signal = gausspulse(time, fc=frq, bw=bw, bwr=bwr, retquad=False, retenv=False) elif retquad is True: _, signal = gausspulse(time, fc=frq, bw=bw, bwr=bwr, retquad=True, retenv=False) signal = signal * ampl signal_center = np.argmin(np.abs(time)) signal = signal.reshape(-1, 1) return (signal, signal_center)
def run(): import seg1d import numpy as np import matplotlib.pylab as plt import scipy.signal as signal # create an array of data x = np.linspace(-1, 1, 2000) # get an array of data from a Gaussian pulse targ = signal.gausspulse(x, fc=5) # define a segment within the pulse to use as reference t_s, t_e = 950, 1050 # cut a segment out to use as a reference data refData = [{'gauss': targ[t_s:t_e]}] targData = {'gauss': targ} refWeights = {'gauss': 1} ### define some test parameters minWin = 98 # minimum percent to scale down reference data maxWin = 105 # maximum percent to scale up reference data sizeStep = 1 # step to use for correlating reference to target data # call the segmentation algorithm segments = seg1d.segment_data(refData, targData, refWeights, minWin, maxWin, sizeStep) print(np.around(segments, decimals=7)) plt.figure(figsize=(15, 4)) # plot the full pulse plt.plot(x, targ, linewidth=6, alpha=0.2, label='Target') # plot the original reference segment plt.plot(x[t_s:t_e], targ[t_s:t_e], linewidth=8, alpha=0.5, label='Reference') # plot all segments found seg_num = 1 for s, e, c in segments: plt.plot(x[s:e], targ[s:e], dashes=[0.5, 0.5], linewidth=4, alpha=0.8, label='Segment {}'.format(seg_num)) plt.legend() plt.show()
def ping(self, positions, delays=None, show=False): """Send delayed pings at the given positions. Positions are relative to the center of the field. Args: positions: Positions to send and receive pings, relative to the center of the field. delays: Delay of the pings. show: Animate the simulation. Returns: Returned signals. """ # Reset field to allow for repeated execution. self.field.pressure.values = np.zeros_like(self.field.pressure.values) self.field.velocity_x.values = np.zeros_like(self.field.velocity_x.values) self.field.velocity_y.values = np.zeros_like(self.field.velocity_y.values) self.field.step = 0 if delays is None: delays = np.zeros(len(positions)) for position, delay in zip(positions, delays): self.field.pressure.add_boundary( self.field.get_point_region( position=(self.field.x.vector[len(self.field.x.vector) // 2] + position, max(self.field.y.vector))), value=sg.gausspulse(self.field.t.vector - self.ping_pre_delay - delay, self.ping_frequency, self.ping_bandwidth), additive=True) self.field.pressure.add_output( self.field.get_point_region( position=(self.field.x.vector[len(self.field.x.vector) // 2] + position, max(self.field.y.vector)))) if show: animator = fd.Animator2D(field=self.field, scale=0.1) animator.show_boundaries = False animator.show_materials = False animator.show_output = False animator.start_simulation() else: self.field.simulate() if self.postprocessor: return self.postprocessor( [output.mean_signal for output in self.field.pressure.outputs]) else: return [output.mean_signal for output in self.field.pressure.outputs]
def test_whiten(self): # create noise with a glitch in it at 1000 Hz noise = self.random.zpk([], [0], 1) glitchtime = 0.5 glitch = signal.gausspulse(noise.times.value + glitchtime, bw=100) * 1e-4 data = noise + glitch # whiten and test that the max amplitude is recovered at the glitch tmax = data.times[data.argmax()] self.assertNotAlmostEqual(tmax.value, -glitchtime) whitened = data.whiten(2, 1) self.assertEqual(noise.size, whitened.size) self.assertAlmostEqual(whitened.mean().value, 0.0, places=4) tmax = whitened.times[whitened.argmax()] self.assertAlmostEqual(tmax.value, -glitchtime)
def plotGpulse(self, amp, freq): self.Fs: int = 44100 self.x = arange(0, 1, 1 / self.Fs) self.y = (amp / 10) * gausspulse((self.x, freq)) self.plot = self.PlotView.plotItem self.vBox = self.plot.vb self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2) self.vBox.setBackgroundColor("w") self.plot.addLegend() self.plot.showGrid(x=True, y=True) self.plot.plot(self.x, self.y, pen=mkPen('b', width=1), name=str(amp) + "Gaussian Pulse(2π" + str(freq))
def test_whiten(self): # create noise with a glitch in it at 1000 Hz noise = self.random.zpk([], [0], 1) glitchtime = 0.5 glitch = signal.gausspulse( noise.times.value + glitchtime, bw=100) * 1e-4 data = noise + glitch # whiten and test that the max amplitude is recovered at the glitch tmax = data.times[data.argmax()] self.assertNotAlmostEqual(tmax.value, -glitchtime) whitened = data.whiten(2, 1) self.assertEqual(noise.size, whitened.size) self.assertAlmostEqual(whitened.mean(), 0.0, places=5) tmax = whitened.times[whitened.argmax()] self.assertAlmostEqual(tmax.value, -glitchtime)
def gausspulse(mean, std, start, end): #t = np.linspace(-10, 10, 2 * 100, endpoint=False) gausspulse = np.zeros((data_points)) num_data_points = int(data_points * (end - start)) start_zeros = np.zeros((int(data_points * start))) t = np.linspace(-1, 1, num_data_points) #t_year = np.linspace(-1, 1, num_minutes_in_year) i, q, e = signal.gausspulse(t, fc=2, retquad=True, retenv=True) i *= std i += mean final = np.append(start_zeros, i) trailing_zeros = np.zeros(np.shape(gausspulse)[0] - np.shape(final)[0]) final2 = np.append(final, trailing_zeros) gausspulse += final2 #plt.plot(t_year,gausspulse) return gausspulse
def scalogram_example_1(): if True: #N = 30 N = 1000 t = np.linspace(-1, 1, N, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) else: # A signal given. sig = ... N = len(sig) t = np.linspace(0, 1 / Fs * N, N + 1)[:N] widths = np.arange(1, N + 1) #widths = np.arange(1, 500 + 1) # Compute the CWT. cwtmatr = signal.cwt(sig, signal.ricker, widths) # cwtmatr.shape = (len(widths), len(sig)). # Scalogram: a spectrogram for wavelets. (???) plt.figure() plt.pcolormesh(t, widths, 20 * np.log10(np.abs(cwtmatr))) #plt.pcolormesh(t, widths[:500], 20 * np.log10(np.abs(cwtmatr[:500,:]))) plt.title('Scalogram') #plt.xlabel('?') #plt.ylabel('?') plt.tight_layout() # Plot the CWT. plt.figure() #plt.imshow(cwtmatr, extent=[t[0], t[-1], widths[0], widths[-1]], cmap='PRGn', aspect='auto', vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) plt.imshow(cwtmatr, extent=[t[0], t[-1], widths[-1], widths[0]], cmap='PRGn', aspect='auto', vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) #plt.imshow(cwtmatr[:200,:], extent=[t[0], t[-1], widths[200], widths[0]], cmap='PRGn', aspect='auto', vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) plt.title('CWT') #plt.xlabel('?') #plt.ylabel('?') plt.tight_layout() plt.show()
def test_whiten(self): # create noise with a glitch in it at 1000 Hz noise = self.TEST_CLASS(numpy.random.normal(loc=1, size=16384 * 10), sample_rate=16384, epoch=-5).zpk([], [0], 1) glitchtime = 0.5 glitch = signal.gausspulse(noise.times.value + glitchtime, bw=100) * 1e-4 data = noise + glitch # whiten and test that the max amplitude is recovered at the glitch tmax = data.times[data.argmax()] assert not numpy.isclose(tmax.value, -glitchtime) whitened = data.whiten(2, 1) assert noise.size == whitened.size nptest.assert_almost_equal(whitened.mean().value, 0.0, decimal=4) tmax = whitened.times[whitened.argmax()] nptest.assert_almost_equal(tmax.value, -glitchtime)
def gen_test_data(plot=False): """ Generate factor matrices which components will be easy to differentiate from one another Parameters ---------- plot : bool Returns ------- fmat : list[np.ndarray] core_values : np.ndarray """ t_A = np.linspace(0, 1, 500, endpoint=False).reshape(-1, 1) t_B = np.linspace(0, 2, 10, endpoint=False).reshape(-1, 1) t_C = np.linspace(-1, 1, 2 * 100, endpoint=False).reshape(-1, 1) w_A = np.array([1, 2, 5]).reshape(-1, 1) w_B = np.roll(w_A, 1) w_C = np.array([0.3, 2, 0.7]).reshape(-1, 1) A = np.sin (2 * np.pi * t_A * w_A.T) B = signal.square (2 * np.pi * t_B * w_B.T) C, _, _ = signal.gausspulse(t_C * w_C.T, fc=5, retquad=True, retenv=True) fmat = [A, B, C] core_values = np.array([1]*A.shape[1]) if plot: for mode, factor in enumerate(fmat): print("Mode-{} factor matrix shape = {}".format(mode, factor.shape)) fig, axis = plt.subplots(nrows=3, ncols=1, figsize=(8, 8) ) axis[0].plot(t_A, A) axis[0].set_title("Factor matrix A") axis[1].plot(t_B, B) axis[1].set_title("Factor matrix B") axis[2].plot(t_C, C) axis[2].set_title("Factor matrix C") plt.tight_layout() return fmat, core_values
def test_correlate(self): # create noise and a glitch template at 1000 Hz noise = self.TEST_CLASS( numpy.random.normal(size=16384 * 64), sample_rate=16384, epoch=-32 ).zpk([], [1], 1) glitchtime = -16.5 glitch = self.TEST_CLASS( signal.gausspulse(numpy.arange(-1, 1, 1./16384), bw=100), sample_rate=16384, epoch=glitchtime-1) # check that, without a signal present, we only see background snr = noise.correlate(glitch, whiten=True) tmax = snr.times[snr.argmax()] assert snr.size == noise.size assert not numpy.isclose(tmax.value, glitchtime) nptest.assert_almost_equal(snr.mean().value, 0.0, decimal=1) nptest.assert_almost_equal(snr.std().value, 1.0, decimal=1) # inject and recover the glitch data = noise.inject(glitch * 1e-4) snr = data.correlate(glitch, whiten=True) tmax = snr.times[snr.argmax()] nptest.assert_almost_equal(tmax.value, glitchtime)
def test_save_loudest_tile_features(): # prepare input data channel = GW.channels[0] noise = TimeSeries( numpy.random.normal(loc=1, scale=.5, size=16384 * 68), sample_rate=16384, epoch=-34).zpk([], [0], 1) glitch = TimeSeries( signal.gausspulse(numpy.arange(-1, 1, 1./16384), bw=100), sample_rate=16384, epoch=-1) * 1e-4 in_ = noise.inject(glitch) _, _, _, qgram, _, _, _ = core.scan( gps=0, channel=channel, xoft=in_, resample=4096, fftlength=8) # test loudest tiles channel.save_loudest_tile_features(qgram, correlate=glitch) assert channel.Q == numpy.around(qgram.plane.q, 1) assert channel.energy == numpy.around(qgram.peak['energy'], 1) assert channel.snr == numpy.around(qgram.peak['snr'], 1) assert channel.t == numpy.around(qgram.peak['time'], 3) assert channel.f == numpy.around(qgram.peak['frequency'], 1) assert channel.corr == numpy.around(glitch.max().value, 1) assert channel.delay == 0.0 assert channel.stdev == glitch.std().value
from scipy import signal import matplotlib.pyplot as plt import numpy as np t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) fig1,handler = plt.subplots() handler.grid(True) handler.plot(t,sig) # widths = np.arange(1, 31) cwtmatr = signal.cwt(sig, signal.ricker, widths) fig2,handler2 = plt.subplots() plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) #handler2.plt.show() plt.show()
from .. import qtransform from ...table import EventTable from ...segments import Segment from ...timeseries import TimeSeries __author__ = 'Alex Urban <*****@*****.**>' # -- global variables --------------------------------------------------------- # create noise and a glitch template at 1000 Hz NOISE = TimeSeries( numpy.random.normal(size=4096 * 10), sample_rate=4096, epoch=-5) GLITCH = TimeSeries( gausspulse(NOISE.times.value, fc=500)*10, sample_rate=4096) DATA = NOISE + GLITCH # global test objects SEARCH = Segment(-0.25, 0.25) QGRAM, FAR = qtransform.q_scan(DATA, search=SEARCH) QSPECGRAM = QGRAM.interpolate() # -- test utilities ----------------------------------------------------------- def test_far(): # test that FAR is better than 1 / Hubble time assert FAR < 1 / (1.37e10 * 365 * 86400)
def gausspulse(self): return [ self.K * u for u in signal.gausspulse( t = self.t, fc = self.f) ]
# Plot real component, imaginary component, and envelope for a 5 Hz pulse, # sampled at 100 Hz for 2 seconds: from scipy import signal import matplotlib.pyplot as plt t = np.linspace(-1, 1, 2 * 100, endpoint=False) i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True) plt.plot(t, i, t, q, t, e, '--')
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 18:13:27 2015 @author: NigmatullinR """ #пример связ с Гаусовским импульсом import numpy as np import pylab as plb import scipy.signal as sgn M=2 # decimation factor t = np.linspace(-0.75, 0.75, 2 * 100, endpoint=False)#носитель на кот строится ГИ g = sgn.gausspulse(t, fc=5, bw=0.3, retquad=False, retenv=False)#Гаус импульс plb.plot(t, g) plb.title('Original signal') plb.figure() plb.plot(abs(np.fft.fft(g)[:len(g)/2]))#преобр Ф plb.title('Original signal FFT') ind2=range(0,len(g),2) g2=g[ind2] plb.figure() plb.plot(g2) plb.title('Signal after decimation') plb.figure()
def myfnc(t): return sig.gausspulse(t, fc = 0.07)
from numpy.random import normal from scipy.signal import gausspulse from gwpy.timeseries import TimeSeries # Generate a `TimeSeries` containing Gaussian noise sampled at 4096 Hz, # centred on GPS time 0, with a sine-Gaussian pulse ('glitch') at # 500 Hz: noise = TimeSeries(normal(loc=1, size=4096*4), sample_rate=4096, epoch=-2) glitch = TimeSeries(gausspulse(noise.times.value, fc=500) * 4, sample_rate=4096) data = noise + glitch # Compute and plot the Q-transform of these data: q = data.q_transform() plot = q.plot() ax = plot.gca() ax.set_xlim(-.2, .2) ax.set_epoch(0) plot.show()
sim_fixed.set_parameter("verbose", "0"); sim_spline.set_parameter("verbose", "0") sim_fixed.set_print_debug(False); sim_spline.set_print_debug(False) sim_fixed.set_parameter("sound_speed", "%f" % c0); sim_spline.set_parameter("sound_speed", "%f" % c0) sim_fixed.set_parameter("phase_delay", "on"); sim_spline.set_parameter("phase_delay", "on") sim_fixed.set_parameter("radial_decimation", "5"); sim_spline.set_parameter("radial_decimation", "5") num_gpus = int(sim_fixed.get_parameter("num_cuda_devices")) print "System has %d CUDA devices" % num_gpus sim_fixed.set_parameter("gpu_device", "%d" % args.gpu_device_no) sim_spline.set_parameter("gpu_device", "%d" % args.gpu_device_no) print "Fixed simulator uses %s" % sim_fixed.get_parameter("cur_device_name") print "Spline simulator uses %s" % sim_spline.get_parameter("cur_device_name") # define excitation signal t_vector = np.arange(-16/args.fc, 16/args.fc, 1.0/args.fs) samples = np.array(gausspulse(t_vector, bw=args.bw, fc=args.fc), dtype="float32") center_index = int(len(t_vector)/2) demod_freq = args.fc sim_fixed.set_excitation(samples, center_index, args.fs, demod_freq) sim_spline.set_excitation(samples, center_index, args.fs, demod_freq) # create big scan sequence with all M-mode beams (for the spline algorithm) origins = np.empty((args.num_beams_total, 3), dtype="float32") directions = np.empty((args.num_beams_total, 3), dtype="float32") lateral_dirs = np.empty((args.num_beams_total, 3), dtype="float32") y_axis = np.array([0.0, 1.0, 0.0]) lateral_dir = np.cross(y_axis, direction) for beam_no in range(args.num_beams_total): origins[beam_no, :] = origin directions[beam_no, :] = direction lateral_dirs[beam_no, :] = lateral_dir
fc_upp=1000 a, b = truncparms(fc_low, fc_upp, fc_mu, fc_sigma) fcs = stats.truncnorm.rvs(a, b, loc=fc_mu, scale=fc_sigma, size=Nwaveforms) # bandwidth bw_mu=0.005 bw_sigma=0.001 bw_low=0.0001 bw_upp=0.1 a, b = truncparms(bw_low, bw_upp, bw_mu, bw_sigma) bws = stats.truncnorm.rvs(a, b, loc=bw_mu, scale=bw_sigma, size=Nwaveforms) # populate catalogue win = lal.CreateTukeyREAL8Window(len(time_axis), 0.1) for i in xrange(Nwaveforms): catalogue[:,i] = win.data.data*signal.gausspulse(time_axis, fcs[i], bws[i]) catalogue[:,i] /= np.sqrt(np.dot(catalogue[:,i], catalogue[:,i])) # # Chirps # chirp_times = np.arange(0, datalen, 1.0/Fs) idx = chirp_times<=0.5 win = lal.CreateTukeyREAL8Window(int(sum(idx)), 0.1) tau=0.5 f0=100 t1=0.5 f1_mu = 500 f1_sigma = 100
Just half sampling of group3 otus. ''' ts_g6_otus = ts_g3_otus.take(arange(0,74,2),1).astype(int) ############### # group7 otus # ############### ''' These otus will include a pulse for some of the samples. The pulses are all shifted by one sample, and also includes their envelope. Here, the center frequency is 1Hz ''' #make pulse of 50 points, with amplitude 200 t = linspace(-3, 3, 1*50, endpoint=False) real, envelope = gausspulse(t, fc=1, retenv=True) real = 200*(real+1) envelope = 200*(envelope+1) # plt.plot(t, i, t, e, '--') # plt.show() samples = linspace(0, 199, 200) otu_real =[[0 for a in range(200)] for k in range(200)] otu_envelope =[[0 for a in range(200)] for k in range(200)] #insert pulse into 150 point vector of average amplitude #at different indices for total length of 200 for j in samples: z = [200]*150 j = int(j) for x in real:
import numpy import scipy import matplotlib.pyplot as plt x=numpy.linspace(-1, 1, 1000) t=numpy.linspace(-3*numpy.pi,3*numpy.pi,1000) from scipy.signal import chirp, sawtooth, square, gausspulse plt.figure() plt.subplot(221) plt.plot(x,chirp(x,f0=100,t1=0.5,f1=200)) plt.ylim([-2,2]) plt.subplot(222) plt.plot(x,gausspulse(x,fc=10, bw=0.5)) plt.ylim([-2,2]) plt.subplot(223) plt.plot(t,sawtooth(t)) plt.ylim([-2,2]) plt.subplot(224) plt.plot(t,square(t)) plt.ylim([-2,2]) plt.show()
def do_simulation(args): if args.use_gpu: sim = RfSimulator("gpu") sim.set_parameter("gpu_device", "%d"%args.device_no) gpu_name = sim.get_parameter("cur_device_name") print "Using device %d: %s" % (args.device_no, gpu_name) else: sim = RfSimulator("cpu") sim.set_parameter("verbose", "0") with h5py.File(args.h5_file, "r") as f: scatterers_data = f["data"].value sim.add_fixed_scatterers(scatterers_data) print "The number of scatterers is %d" % scatterers_data.shape[0] # configure simulation parameters sim.set_parameter("sound_speed", "1540.0") sim.set_parameter("radial_decimation", "10") sim.set_parameter("phase_delay", "on") sim.set_parameter("noise_amplitude", "%f" % args.noise_ampl) # configure the RF excitation fs = 80e6 ts = 1.0/fs fc = 5.0e6 tc = 1.0/fc t_vector = np.arange(-16*tc, 16*tc, ts) bw = 0.3 samples = np.array(gausspulse(t_vector, bw=bw, fc=fc), dtype="float32") center_index = int(len(t_vector)/2) sim.set_excitation(samples, center_index, fs, fc) # define the scan sequence origins = np.zeros((args.num_lines, 3), dtype="float32") origins[:,0] = np.linspace(args.x0, args.x1, args.num_lines) x_axis = np.array([1.0, 0.0, 0.0]) z_axis = np.array([0.0, 0.0, 1.0]) directions = np.array(np.tile(z_axis, (args.num_lines, 1)), dtype="float32") length = 0.06 lateral_dirs = np.array(np.tile(x_axis, (args.num_lines, 1)), dtype="float32") timestamps = np.zeros((args.num_lines,), dtype="float32") sim.set_scan_sequence(origins, directions, length, lateral_dirs, timestamps) # configure the beam profile sim.set_analytical_beam_profile(1e-3, 1e-3) frame_sim_times = [] for frame_no in range(args.num_frames): start_time = time() iq_lines = sim.simulate_lines() frame_sim_times.append(time()-start_time) if args.save_simdata_file != "": with h5py.File(args.save_simdata_file, "w") as f: f["sim_data_real"] = np.array(np.real(iq_lines), dtype="float32") f["sim_data_imag"] = np.array(np.imag(iq_lines), dtype="float32") print "Simulation output written to %s" % args.save_simdata_file print "Simulation time: %f +- %f s (N=%d)" % (np.mean(frame_sim_times), np.std(frame_sim_times), args.num_frames) if args.pdf_file != "" and not args.visualize: import matplotlib as mpl mpl.use("Agg") if args.pdf_file != "" or args.visualize: import matplotlib.pyplot as plt num_samples, num_lines = iq_lines.shape plt.figure(1, figsize=(18,9)) plt.subplot(1,2,1) plt.plot(np.real(iq_lines[:, num_lines/2])) plt.title("Middle RF line") plt.subplot(1,2,2) plt.imshow(np.real(abs(iq_lines)), aspect="auto", interpolation="nearest") if args.pdf_file != "": plt.savefig(args.pdf_file) print "Image written to disk." if args.visualize: plt.show()