Download this notebook by clicking on the download icon
or find it in the repository
PacificSound256kHzTo2kHzDecimate
- Distributed under the terms of the GPL License
- Maintainer: yzhang@mbari.org
- Authors: Yanwu Zhang yzhang@mbari.org, Paul McGill mcgill@mbari.org, Danelle Cline (dcline@mbari.org), John Ryan ryjo@mbari.org
Decimation of MARS hydrophone data¶
An extensive (6+ years and growing) archive of sound recordings from a deep-sea location along the eastern margin of the North Pacific Ocean has been made available through AWS Open data. Temporal coverage of the recording archive has been 95% since project inception in July 2015. The original recordings have a sample rate of 256 kHz. Many research topics can be effectively studied using data with a lower sample rate, and this Open Data project includes daily files decimated to 2 kHz and 16 kHz. The purpose of this notebook is to illustrate a method of optimizing decimation processing, which is applicable to any desired sample rate. The demonstration uses Python, but the algorithms can be implemented in other languages.
This method enables design of the optimal windowed-sinc anti-aliasing low-pass filter (using a certain window) that meets the desired passband and stopband requirements based on signal retention and exclusion needs. The best combination of the sinc function’s cutoff frequency and the main-lobe bandwidth of the window function generates the shortest qualifying filter.
If you use this data set, please cite our project.
Data Overview¶
The full-resolution audio data are in WAV format in s3 buckets named pacific-sound-256khz-yyyy, where yyyy is 2015 or later. Buckets are stored as objects, so the data aren't physically stored in folders or directories as you may be familiar with, but you can think of it conceptually as follows:
pacific-sound-256khz-2021
|
individual 10-minute files
Install required dependencies¶
First, let's install the required software dependencies.
If you are using this notebook in a cloud environment, select a Python3 compatible kernel and run this next section. This only needs to be done once for the duration of this notebook.
If you are working on local computer, you can skip this next cell. Change your kernel to pacific-sound-notebooks, which you installed according to the instructions in the README - this has all the dependencies that are needed.
!pip install -q boto3 --quiet
!pip install -q soundfile --quiet
!pip install -q scipy --quiet
!pip install -q numpy --quiet
!pip install -q matplotlib --quiet
|████████████████████████████████| 132 kB 4.7 MB/s
|████████████████████████████████| 79 kB 5.3 MB/s
|████████████████████████████████| 9.2 MB 40.3 MB/s
|████████████████████████████████| 140 kB 20.1 MB/s
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
requests 2.23.0 requires urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1, but you have urllib3 1.26.12 which is incompatible.
Import all packages¶
import boto3
from botocore import UNSIGNED
from botocore.client import Config
from six.moves.urllib.request import urlopen
import io
import math
import scipy
from scipy import signal, interpolate
import numpy as np
import soundfile as sf
import matplotlib.pyplot as plt
List the contents of a monthly directory¶
s3 = boto3.client('s3',
aws_access_key_id='',
aws_secret_access_key='',
config=Config(signature_version=UNSIGNED))
bucket = 'pacific-sound-256khz-2021'
for i, obj in enumerate(s3.list_objects_v2(Bucket=bucket)['Contents']):
print(obj['Key'])
if i > 20:
break
01/MARS_20210101_000424.wav 01/MARS_20210101_001424.wav 01/MARS_20210101_002424.wav 01/MARS_20210101_003424.wav 01/MARS_20210101_004424.wav 01/MARS_20210101_005424.wav 01/MARS_20210101_010424.wav 01/MARS_20210101_011424.wav 01/MARS_20210101_012424.wav 01/MARS_20210101_013424.wav 01/MARS_20210101_014424.wav 01/MARS_20210101_015424.wav 01/MARS_20210101_020424.wav 01/MARS_20210101_021424.wav 01/MARS_20210101_022424.wav 01/MARS_20210101_023424.wav 01/MARS_20210101_024424.wav 01/MARS_20210101_025424.wav 01/MARS_20210101_030424.wav 01/MARS_20210101_031424.wav 01/MARS_20210101_032424.wav 01/MARS_20210101_033424.wav
Read metadata from a file¶
bucket = 'pacific-sound-256khz-2021'
filename = '09/MARS_20210915_070829.wav'
url = f'https://{bucket}.s3.amazonaws.com/{filename}'
print(f'Reading metadata from {url}')
sf.info(io.BytesIO(urlopen(url).read(1000)), verbose=True)
Reading metadata from https://pacific-sound-256khz-2021.s3.amazonaws.com/09/MARS_20210915_070829.wav
<_io.BytesIO object at 0x7fcdb059ea10> samplerate: 256000 Hz channels: 1 duration: 218 samples format: WAV (Microsoft) [WAV] subtype: Signed 24 bit PCM [PCM_24] endian: FILE sections: 1 frames: 218 extra_info: """ Length : 1000 RIFF : 460800336 (should be 992) WAVE LIST : 292 INFO IART : icListen HF #1689 IPRD : RB9-ETH R4 ICRD : 2021-09-15T07:08:29+00 ISFT : Lucy V4.3.6 INAM : MARS_20210915_070829.wav ICMT : 3.000000 V pk, -177 dBV re 1uPa, 44.0 % RH, 6.0 deg C, 8388608 = Max Count fmt : 16 Format : 0x1 => WAVE_FORMAT_PCM Channels : 1 Sample Rate : 256000 Block Align : 3 Bit Width : 24 Bytes/sec : 768000 data : 460800000 (should be 656) End """
Read data from a file¶
print(f'Reading data from {url}')
x, sample_rate = sf.read(io.BytesIO(urlopen(url).read()),dtype='float32')
Reading data from https://pacific-sound-256khz-2021.s3.amazonaws.com/09/MARS_20210915_070829.wav
Produce a spectrogram¶
Calibrated Spectrum Levels¶
Calibration metadata¶
Frequency-dependent hydrophone sensitivity data are defined in the following files, one for each deployment:
Compute spectrogram¶
# convert scaled voltage to volts
v = x*3
nsec = (v.size)/sample_rate # number of seconds in vector
spa = 1 # seconds per average
nseg = int(nsec/spa)
print(f'{nseg} segments of length {spa} seconds in {nsec} seconds of audio')
600 segments of length 1 seconds in 600.0 seconds of audio
lenfft_input = 2**int(np.ceil(np.log2(sample_rate)))
print(lenfft_input)
#
# initialize empty LTSA
nfreq = int(lenfft_input/2+1)
sg_input = np.empty((nfreq, nseg), float)
sg_input.shape
262144
(131073, 600)
# get window
w_input = scipy.signal.get_window('blackman',sample_rate)
window_correction = np.mean(np.square(w_input))
#
numDataPoints_input = int(sample_rate*spa)
#
Ind_keep = np.arange(0, int(lenfft_input/2)+1)
f_input = (Ind_keep/lenfft_input) * sample_rate
#
# Calculate spectrogram
for x in range(0,nseg):
cstart = x*spa*sample_rate
cend = (x+1)*spa*sample_rate
# f,psd = scipy.signal.welch(v[cstart:cend], fs=sample_rate, window=w_input, nfft=sample_rate)
psd_input = np.square(np.absolute(np.fft.fft(np.multiply(v[cstart:cend],w_input), n=lenfft_input)))/(numDataPoints_input*window_correction)/sample_rate
psd_input_log10 = 10*np.log10(psd_input[Ind_keep])
sg_input[:,x] = psd_input_log10
if (x == 0):
psd_input_check = psd_input
print("Comparing power of the input signal computed in the time domain versus that computed in the frequency domain:")
print(np.mean(np.square(v[cstart:cend])))
print(sum(psd_input_check)*(sample_rate/lenfft_input))
Comparing power of the input signal computed in the time domain versus that computed in the frequency domain: 0.00012095761 0.000121922813689169
Apply calibration¶
Frequency-dependent hydrophone sensitivity data are reported in the json files identified above. This example file is from the second hydrophone deployment, for which the calibration data are manually entered below. Note that the lowest measured value, at 250 Hz, is assumed to cover lower frequencies and repeated as a value at 0 Hz to allow interpolation to the spectrogram output frequencies across the full frequency range.
# define hydrophone calibration data
calfreq = [0,250,10000,20100,30100,40200,50200,60200,70300,80300,90400,100400,110400,120500,130500,140500,150600,160600,170700,180700,190700,200000]
calsens = [-177.90,-177.90,-176.80,-176.35,-177.05,-177.35,-177.30,-178.05,-178.00,-178.40,-178.85,-180.25,-180.50,-179.90,-180.15,-180.20,-180.75,-180.90,-181.45,-181.30,-180.75,-180.30]
# interpolate to the frequency resolution of the spectrogram
tck = interpolate.splrep(calfreq, calsens, s=0)
isens = interpolate.splev(f_input, tck, der=0)
plt.figure(dpi=300)
im = plt.plot(calfreq,calsens,'bo',f_input,isens,'g')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Hydrophone sensitivity (dB re V/uPA)')
plt.legend(['Factory, measured', 'Interpolated'])
<matplotlib.legend.Legend at 0x7fcdaffa0750>
# replicate interpolated sensitivity
isensg = np.transpose(np.tile(isens,[nseg,1]))
isensg.shape
(131073, 600)
sg_input.shape
(131073, 600)
Plot the calibrated spectrogram¶
plt.figure(dpi=300)
im = plt.imshow(sg_input-isensg,aspect='auto',origin='lower',vmin=28,vmax=95)
plt.yscale('log')
plt.ylim(10,100000)
plt.colorbar(im)
plt.xlabel('Seconds')
plt.ylabel('Frequency (Hz)')
plt.title('Calibrated spectrum levels (dB) of the 256 kHz sample-rate input data')
Text(0.5, 1.0, 'Calibrated spectrum levels (dB) of the 256 kHz sample-rate input data')