def main(): parser = argparse.ArgumentParser() parser.add_argument('source', type=str) parser.add_argument('target', type=str) args = parser.parse_args() filenames = os.listdir(args.source) paths = (os.path.join(args.source, filename) for filename in filenames) signals = list(map(load_signal, paths)) # Create spectrograms plotargs = { 'clim': (-40, +40), 'title': '', } # Create spectrograms for signal in signals: create_spectrogram( signal, os.path.join(args.target, "{}.{}".format(signal.basename, EXTENSION)), plotargs) # Time-level s = Signal(signals, signals[0].fs) name = os.path.join(args.target, "levels.{}".format(EXTENSION)) ax = s.plot_levels() ax.legend(labels=[ create_label(signal.method, signal.kernelsize) for signal in signals ]) fig = ax.get_figure() fig.tight_layout() fig.savefig(name, dpi=600)
def create_figure(source, target): s, meta = h5load(source) s = Signal(s, meta['fs']) ax = s.plot_spectrogram(clim=CLIM, ylim=YLIM, title='') fig = ax.get_figure() fig.tight_layout() fig.savefig(target, dpi=600)
def create_figure(source, target): s, meta = h5load(source) s = Signal(s, meta['fs']) ax = s.plot_spectrogram(ylim=YLIM, clim=CLIM, title='') fig = ax.get_figure() #fig.subplots_adjust(bottom=0.2, left=0.2) fig.tight_layout() fig.savefig(target, dpi=600)
def load_signal(path): """Load signal. :returns: `(signal, method, kernelsize, basename)` """ s, meta = h5load(path) s = Signal(s, meta['fs']) s.method = meta['method'] s.kernelsize = meta['kernelsize'] s.basename = os.path.splitext(os.path.basename(path))[0] return s
def create_figure(source, target, plotargs=None): if plotargs is None: plotargs = {} s, meta = h5load(source) s = Signal(s, meta['fs']) ax = s.plot_spectrogram(clim=CLIM, xlim=XLIM, ylim=YLIM, title='', **plotargs) fig = ax.get_figure() #fig.subplots_adjust(bottom=0.2, left=0.2) fig.tight_layout() fig.savefig(target, dpi=600)
def __getitem__(self, t): df = self._map(t).reset_index() s = None for f in df['file_path']: if s is None: s = Signal.from_wav(f) else: s = join(s, Signal.from_wav(f)) # further triming i0 = int((t.start - df['time'].iloc[0]).seconds * s.fs) i1 = i0 + (t.stop - t.start).seconds * s.fs #print(i0,i1,i1-i0,s.shape, s[i0:i1].shape, s.fs) s = s[i0:i1] #s = Signal(s[i0:i1], s.fs) t = df['time'].iloc[0] + pd.Timedelta(i0 / s.fs, unit='seconds') return s, t
class test_wav(): """Test writing to and reading from wav file.""" duration = 5.0 fs = 10025 samples = int(fs * duration) channels = 3 signal = Signal(np.random.randn(channels, samples), fs) with tempfile.TemporaryFile() as file: signal.to_wav(file) signal = Signal.from_wav(file) assert signal.samples == samples assert signal.fs == fs assert signal.channels == channels
def test_calibrate_with(self, signal): calibration_signal_level = 50.0 decibel = 94.0 calibration_signal = Signal(np.random.randn(signal.samples), signal.fs).calibrate_to(calibration_signal_level) out = signal.calibrate_with(calibration_signal, decibel) assert ( (out.leq() - signal.leq()).mean() - (decibel - calibration_signal_level) ) < 0.01
def test_tonality(): duration = 60.0 fs = 10025.0 samples = int(fs * duration) times = np.arange(samples) / fs signal = Signal(np.sin(2.0 * np.pi * 1000.0 * times), fs) tonality = Tonality(signal, signal.fs) # Test methods before analysis tonality.spectrum tonality.plot_spectrum() tonality.frequency_resolution tonality.effective_analysis_bandwidth # No values yet, cannot print overview. with pytest.raises(ValueError): print(tonality.overview()) tonality.results_as_dataframe() assert len(list(tonality.noise_pauses)) == 0 assert len(list(tonality.tones)) == 0 assert len(list(tonality.critical_bands)) == 0 # Perform analysis tonality.determine_noise_pauses().analyse() # Needs to be checked #assert len(list(tonality.noise_pauses)) == 1 #assert len(list(tonality.tones)) == 1 #assert len(list(tonality.critical_bands)) == 1 tonality.critical_band_at(900.0) tonality.dominant_tone print(tonality.overview()) tonality.results_as_dataframe() tonality.plot_results()
def load_signal(filename): path = os.path.join(args.source, filename) signal = Signal.from_wav(path) _, event, _, kind, part = os.path.splitext(filename)[0].split('-') aircraft = event.split('_')[-1] return {'aircraft': aircraft, 'kind': kind, 'part': part, 'signal': signal}
def main(): # Without turbulence #model.settings['turbulence']['include'] = False model.settings['turbulence']['include'] = False model.settings['turbulence']['amplitude'] = False model.settings['turbulence']['phase'] = False signal = mono(rcv.auralise()) signal = Signal(signal.take(nsamples).toarray(), fs) without = signal # With turbulence (logamp) model.settings['turbulence']['include'] = True model.settings['turbulence']['amplitude'] = True model.settings['turbulence']['phase'] = False signal = mono(rcv.auralise()) signal = Signal(signal.take(nsamples).toarray(), fs) #_ = signal.plot_spectrogram(ylim=(0.0, 4000.0), clim=(-40, +60)) with_logamp = signal # With turbulence (phase) model.settings['turbulence']['include'] = True model.settings['turbulence']['amplitude'] = False model.settings['turbulence']['phase'] = True signal = mono(rcv.auralise()) signal = Signal(signal.take(nsamples).toarray(), fs) # In[21]: #Audio(data=signal, rate=signal.fs) # In[22]: _ = signal.plot_spectrogram(ylim=(0.0, 4000.0), clim=(-40, +60)) # In[23]: with_phase = signal # ## With turbulence (logamp and phase) # In[24]: model.settings['turbulence']['include'] = True model.settings['turbulence']['amplitude'] = True model.settings['turbulence']['phase'] = True signal = mono(rcv.auralise()) signal = Signal(signal.take(nsamples).toarray(), fs) # In[25]: #Audio(data=signal, rate=signal.fs) # In[26]: _ = signal.plot_spectrogram(ylim=(0.0, 4000.0), clim=(-40, +60)) # In[27]: with_logamp_and_phase = signal # In[28]: signals = Signal([without, with_logamp, with_phase, with_logamp_and_phase], fs) # In[29]: labels = ['Without', 'Logamp', 'Phase', 'Both'] # In[30]: fig = signals.plot_levels(labels=labels) # In[31]: _ = signals.plot_third_octaves(labels=labels) # ## Save figures and audio files # In[34]: #with sns.axes_style(rc={"axes.grid":False}): clim = (0.0, +70) ylim = (0.0, 4000.0) for signal, label in zip(signals, labels): signal.normalize().to_wav("../audio/auralisation_flight_{}.wav".format(label.lower())) fig = signal.plot_spectrogram(ylim=ylim, clim=clim, title="") fig.subplots_adjust(bottom=0.2, left=0.2) fig.savefig("../figures/auralisation_flight_{}.eps".format(label.lower()))
def create_audio(source, target): s, meta = h5load(source) s = Signal(s, meta['fs']) s.normalize().to_wav(target)
def join(s1, s2): ''' join two signals ''' assert s1.fs == s2.fs return Signal(np.concatenate([s1, s2]), fs=s1.fs)
def signal(self, request): return Signal(np.random.randn(request.param[0], request.param[1]), request.param[2])
print("Sample frequency: {}".format(fs_min)) logamp, phase = generate_fluctuations_logamp_and_phase( nsamples, fs_min, ntaps_corr, correlation_length, speed, frequency, soundspeed, distance, mean_mu_squared, include_saturation=include_saturation, state=np.random.RandomState(seed=seed), window=window) logamp = Signal(logamp, fs_min) phase = Signal(phase, fs_min) both = Signal([logamp, phase], fs_min) labels = [r'$\chi$', r'$S$'] ax = both.pick(0., 10.).plot(labels=labels, title="", ylabel="Log-amplitude $\chi$, phase $S$") fig = ax.get_figure() fig.tight_layout() savefig(fig, "logamp_and_phase") _tau = tau(ntaps_corr, fs_min) # In[8]: