text_html_output_1.png
import matplotlib.mlab as mlab  # some MATLAB commands

import matplotlib.pyplot as plt  # plotting

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import random    # generating (pseudo)-random numbers

import numpy as np
import pandas as pd
pd.set_option('display.max_colwidth', None)
import matplotlib.pyplot as plt
from glob import glob
import random
import matplotlib.mlab as mlab
from scipy.interpolate import interp1d

training_labels_path = '../input/g2net-gravitational-wave-detection/training_labels.csv'
training_labels = pd.read_csv(training_labels_path)

training_paths = glob('../input/g2net-gravitational-wave-detection/train/*/*/*/*')

ids = [path.split('/')[-1].split('.')[0] for path in training_paths]
paths_df = pd.DataFrame({'path': training_paths, 'id': ids})
train_data = pd.merge(left=training_labels, right=paths_df, on='id')

def load_random_file(signal=None):
    """Selecting a random file from the training dataset. 
    Args:
        signal: bool
            optional flag defining whether to select pure detector 
            noise (False) or detector noise plus simulated signal (True).
            If skipped, the flag is chosen randomly.
    Returns:
        file_id: str
            unique id of the selected file
        target: int
            0 or 1, target value
        data: numpy.ndarray
            numpy array in the shape (3, 4096), where 3 is the number
            of detectors, 4096 is number of data points (each time series
            instance spans over 2 seconds and is sampled at 2048 Hz)
    """
    if signal is None:
        signal = random.choice([True, False])
    filtered = train_data['target'] == signal
    index = random.choice(train_data[filtered].index)
    file_id = train_data['id'].at[index]
    target = train_data['target'].at[index]
    path = train_data['path'].at[index]
    data = np.load(path)
    return (file_id, target, data)

file_id, target, data = load_random_file()
ylim = 1.1*np.max(data)

plt.style.use('ggplot')

fig, axs = plt.subplots(ncols=1, nrows=3, figsize=(10, 5))

for i in range(3):
    ax = axs.ravel()[i]
    ax.plot(data[i])
    ax.margins(0)
    axs[i].set_title(f"Detector {i+1}", loc='center')
    ax.set_ylabel(f"Amplitude")
    ax.set_ylim([-ylim, ylim])
    
axs[0].xaxis.set_visible(False)
axs[1].xaxis.set_visible(False)

axs[2].set_xlabel("Time stamp")
fig.suptitle(f"Raw data visualization. ID: {file_id}. Target: {target}.")
plt.show()

fs = 2048
NFFT = 4 * fs
f_min = 20.0
f_max = fs / 2

_, target, data = load_random_file(True)
strain1, strain2, strain3 = (data[0], data[1], data[2])
Pxx_1, freqs = mlab.psd(strain1, Fs=fs, NFFT=NFFT)
Pxx_2, freqs = mlab.psd(strain2, Fs=fs, NFFT=NFFT)
Pxx_3, freqs = mlab.psd(strain3, Fs=fs, NFFT=NFFT)
psd_1 = interp1d(freqs, Pxx_1)
psd_2 = interp1d(freqs, Pxx_2)
psd_3 = interp1d(freqs, Pxx_3)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 5))
ax.loglog(freqs, np.sqrt(Pxx_1), 'g', label='Detector 1')
ax.loglog(freqs, np.sqrt(Pxx_2), 'r', label='Detector 2')
ax.loglog(freqs, np.sqrt(Pxx_3), 'b', label='Detector 3')
ax.set_xlim([f_min, f_max])
ax.set_ylabel('ASD (strain/$\\sqrt{Hz}$)')
ax.set_xlabel('Frequency (Hz)')
ax.legend()
plt.show()