{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# BINARY BLACK HOLE SIGNALS IN LIGO OPEN DATA \n",
"\n",
"Version 1.41, 2016 July 18\n",
"\n",
"Welcome! This IPython notebook (or associated python script LOSC_Event_tutorial.py ) will go through some typical signal processing tasks on strain time-series data associated with the LIGO Event data releases from the LIGO Open Science Center (LOSC):\n",
"\n",
"* Find events at https://losc.ligo.org/events/.\n",
"* View the tutorial as a web page, for GW150914.\n",
"* Run this tutorial with Binder using the link on the tutorials page.\n",
"* If you are running this tutorial on your own computer, see the Download section below.\n",
"* This notebook works with nbformat version 4. If you are running version 3, pick it up from the tutorials page.\n",
"* After setting the desired \"eventname\" below, you can just run the full notebook.\n",
"\n",
"## Please note that the results obtained here will not match precisely with numbers in our papers, due to various subtleties in the analysis that are discussed further down.\n",
"\n",
"Questions, comments, suggestions, corrections, etc: email losc@ligo.caltech.edu"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Table of Contents\n",
"* Intro to signal processing\n",
"* Download the data\n",
"* Set the event name to choose event and the plot type\n",
"* Read in the data\n",
"* Plot the ASD\n",
"* Binary Neutron Star detection range\n",
"* Whitening\n",
"* Spectrograms\n",
"* Waveform Template\n",
"* Matched filtering to find the signal\n",
"* Make sound Files\n",
"* Data segments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Intro to signal processing\n",
"\n",
"This tutorial assumes that you are comfortable with python.\n",
"\n",
"This tutorial also assumes that you know a bit about signal processing of digital time series data (or want to learn!). This includes power spectral densities, spectrograms, digital filtering, whitening, audio manipulation. This is a vast and complex set of topics, but we will cover many of the basics in this tutorial.\n",
"\n",
"If you are a beginner, here are some resources from the web:\n",
"* http://101science.com/dsp.htm\n",
"* https://www.coursera.org/course/dsp\n",
"* https://georgemdallas.wordpress.com/2014/05/14/wavelets-4-dummies-signal-processing-fourier-transforms-and-heisenberg/\n",
"* https://en.wikipedia.org/wiki/Signal_processing\n",
"* https://en.wikipedia.org/wiki/Spectral_density\n",
"* https://en.wikipedia.org/wiki/Spectrogram\n",
"* http://greenteapress.com/thinkdsp/\n",
"* https://en.wikipedia.org/wiki/Digital_filter\n",
"\n",
"And, well, lots more on the web!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Download the data on a computer with a python installation\n",
"\n",
"If you are using a pre-configured setup (eg, in binder), great! You don't have to download or set up anything.\n",
"\n",
"Otherwise, to begin, get the necessary files, by downloading the zip file and unpacking it into single directory:\n",
"* LOSC_Event_tutorial.zip\n",
"\n",
"This zip file contains:\n",
"\n",
"* this IPython notebook LOSC_Event_tutorial.ipynb, and LOSC_Event_tutorial.py code. \n",
"* python code for reading LOSC data files: readligo.py. \n",
"* the event data files (32s sampled at 4096 Hz, in hdf5 format, for both LIGO detectors).\n",
"* Waveform templates (32s sampled at 4096 Hz, in hdf5 format, for both plus and cross polarizations).\n",
"* a parameter file in json format, O1_events.json .\n",
"\n",
"You will also need a python installation with a few packages (numpy, matplotlib, scipy, h5py, json ).\n",
"\n",
"* For hints on software installation, see https://losc.ligo.org/tutorial00/\n",
"* The tutorial should work on python 2.6 and above, including python 3, as well as in recent versions of Ipython.\n",
"* You *might* see Warning or FutureWarning messages, which tend to be associated with different versions of python, Ipython, numpy, etc. Hopefully they can be ignored!\n",
"* the filetype \"hdf5\" means the data are in hdf5 format:\n",
"https://www.hdfgroup.org/HDF5/\n",
"* NOTE: GPS time is number of seconds since Jan 6, 1980 GMT. See http://www.oc.nps.edu/oc2902w/gps/timsys.html or https://losc.ligo.org/gps/ \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set the event name to choose event and the plot type"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#-- SET ME Tutorial should work with most binary black hole events\n",
"#-- Default is no event selection; you MUST select one to proceed.\n",
"eventname = ''\n",
"# eventname = 'GW150914' \n",
"# eventname = 'GW151226' \n",
"# eventname = 'LVT151012'\n",
"\n",
"# want plots?\n",
"make_plots = 1\n",
"plottype = \"png\"\n",
"#plottype = \"pdf\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Standard python numerical analysis imports:\n",
"import numpy as np\n",
"from scipy import signal\n",
"from scipy.interpolate import interp1d\n",
"from scipy.signal import butter, filtfilt, iirdesign, zpk2tf, freqz\n",
"import h5py\n",
"import json\n",
"\n",
"# the IPython magic below must be commented out in the .py file, since it doesn't work there.\n",
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'retina'\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.mlab as mlab\n",
"\n",
"# LIGO-specific readligo.py \n",
"import readligo as rl\n",
"\n",
"# you might get a matplotlib warning here; you can ignore it."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Read the event properties from a local json file (download in advance):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Read the event properties from a local json file\n",
"fnjson = \"O1_events.json\"\n",
"try:\n",
" events = json.load(open(fnjson,\"r\"))\n",
"except IOError:\n",
" print(\"Cannot find resource file \"+fnjson)\n",
" print(\"You can download it from https://losc.ligo.org/s/events/\"+fnjson)\n",
" print(\"Quitting.\")\n",
" quit()\n",
"\n",
"# did the user select the eventname ?\n",
"try: \n",
" events[eventname]\n",
"except:\n",
" print('You must select an eventname that is in '+fnjson+'! Quitting.')\n",
" quit()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Extract the parameters for the desired event:\n",
"event = events[eventname]\n",
"fn_H1 = event['fn_H1'] # File name for H1 data\n",
"fn_L1 = event['fn_L1'] # File name for L1 data\n",
"fn_template = event['fn_template'] # File name for template waveform\n",
"fs = event['fs'] # Set sampling rate\n",
"tevent = event['tevent'] # Set approximate event GPS time\n",
"fband = event['fband'] # frequency band for bandpassing signal\n",
"print(\"Reading in parameters for event \" + event[\"name\"])\n",
"print(event)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Read in the data\n",
"We will make use of the data, and waveform template, defined above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#----------------------------------------------------------------\n",
"# Load LIGO data from a single file.\n",
"# FIRST, define the filenames fn_H1 and fn_L1, above.\n",
"#----------------------------------------------------------------\n",
"try:\n",
" # read in data from H1 and L1, if available:\n",
" strain_H1, time_H1, chan_dict_H1 = rl.loaddata(fn_H1, 'H1')\n",
" strain_L1, time_L1, chan_dict_L1 = rl.loaddata(fn_L1, 'L1')\n",
"except:\n",
" print(\"Cannot find data files!\")\n",
" print(\"You can download them from https://losc.ligo.org/s/events/\"+eventname)\n",
" print(\"Quitting.\")\n",
" quit()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Gaps\n",
"**NOTE** that in general, LIGO strain time series data has gaps (filled with NaNs) when the detectors are not taking valid (\"science quality\") data. Analyzing these data requires the user to \n",
" loop over \"segments\" of valid data stretches. \n",
"\n",
"**In this tutorial, for simplicity, we assume there are no data gaps - this will not work for all times!** See the \n",
"notes on segments for details.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## First look at the data from H1 and L1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# both H1 and L1 will have the same time vector, so:\n",
"time = time_H1\n",
"# the time sample interval (uniformly sampled!)\n",
"dt = time[1] - time[0]\n",
"\n",
"# Let's look at the data and print out some stuff:\n",
"\n",
"print('time_H1: len, min, mean, max = ', \\\n",
" len(time_H1), time_H1.min(), time_H1.mean(), time_H1.max() )\n",
"print('strain_H1: len, min, mean, max = ', \\\n",
" len(strain_H1), strain_H1.min(),strain_H1.mean(),strain_H1.max())\n",
"print( 'strain_L1: len, min, mean, max = ', \\\n",
" len(strain_L1), strain_L1.min(),strain_L1.mean(),strain_L1.max())\n",
"\n",
"#What's in chan_dict? (See also https://losc.ligo.org/tutorials/)\n",
"bits = chan_dict_H1['DATA']\n",
"print(\"For H1, {0} out of {1} seconds contain usable DATA\".format(bits.sum(), len(bits)))\n",
"bits = chan_dict_L1['DATA']\n",
"print(\"For L1, {0} out of {1} seconds contain usable DATA\".format(bits.sum(), len(bits)))\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# plot +- deltat seconds around the event:\n",
"# index into the strain time series for this time interval:\n",
"deltat = 5\n",
"indxt = np.where((time >= tevent-deltat) & (time < tevent+deltat))\n",
"print(tevent)\n",
"\n",
"if make_plots:\n",
" plt.figure()\n",
" plt.plot(time[indxt]-tevent,strain_H1[indxt],'r',label='H1 strain')\n",
" plt.plot(time[indxt]-tevent,strain_L1[indxt],'g',label='L1 strain')\n",
" plt.xlabel('time (s) since '+str(tevent))\n",
" plt.ylabel('strain')\n",
" plt.legend(loc='lower right')\n",
" plt.title('Advanced LIGO strain data near '+eventname)\n",
" plt.savefig(eventname+'_strain.'+plottype)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The data are dominated by **low frequency noise**; there is no way to see a signal here, without some signal processing."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot the Amplitude Spectral Density (ASD)\n",
"Plotting these data in the Fourier domain gives us an idea of the frequency content of the data. A way to visualize the frequency content of the data is to plot the amplitude spectral density, ASD.\n",
"\n",
"The ASDs are the square root of the power spectral densities (PSDs), which are averages of the square of the fast fourier transforms (FFTs) of the data.\n",
"\n",
"They are an estimate of the \"strain-equivalent noise\" of the detectors versus frequency,\n",
"which limit the ability of the detectors to identify GW signals.\n",
"\n",
"They are in units of strain/rt(Hz).\n",
"So, if you want to know the root-mean-square (rms) strain noise in a frequency band,\n",
"integrate (sum) the squares of the ASD over that band, then take the square-root.\n",
"\n",
"There's a signal in these data! \n",
"For the moment, let's ignore that, and assume it's all noise."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"make_psds = 1\n",
"if make_psds:\n",
" # number of sample for the fast fourier transform:\n",
" NFFT = 4*fs\n",
" Pxx_H1, freqs = mlab.psd(strain_H1, Fs = fs, NFFT = NFFT)\n",
" Pxx_L1, freqs = mlab.psd(strain_L1, Fs = fs, NFFT = NFFT)\n",
"\n",
" # We will use interpolations of the ASDs computed above for whitening:\n",
" psd_H1 = interp1d(freqs, Pxx_H1)\n",
" psd_L1 = interp1d(freqs, Pxx_L1)\n",
"\n",
" # Here is an approximate, smoothed PSD for H1 during O1, with no lines. We'll use it later. \n",
" Pxx = (1.e-22*(18./(0.1+freqs))**2)**2+0.7e-23**2+((freqs/2000.)*4.e-23)**2\n",
" psd_smooth = interp1d(freqs, Pxx)\n",
"\n",
"if make_plots:\n",
" # plot the ASDs, with the template overlaid:\n",
" f_min = 20.\n",
" f_max = 2000. \n",
" plt.figure(figsize=(10,8))\n",
" plt.loglog(freqs, np.sqrt(Pxx_L1),'g',label='L1 strain')\n",
" plt.loglog(freqs, np.sqrt(Pxx_H1),'r',label='H1 strain')\n",
" plt.loglog(freqs, np.sqrt(Pxx),'k',label='H1 strain, O1 smooth model')\n",
" plt.axis([f_min, f_max, 1e-24, 1e-19])\n",
" plt.grid('on')\n",
" plt.ylabel('ASD (strain/rtHz)')\n",
" plt.xlabel('Freq (Hz)')\n",
" plt.legend(loc='upper center')\n",
" plt.title('Advanced LIGO strain data near '+eventname)\n",
" plt.savefig(eventname+'_ASDs.'+plottype)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NOTE that we only plot the data between f_min = 20 Hz and f_max = 2000 Hz.\n",
"\n",
"Below f_min, the data **are not properly calibrated**. That's OK, because the noise is so high below f_min that LIGO cannot sense gravitational wave strain from astrophysical sources in that band.\n",
"\n",
"The sample rate is fs = 4096 Hz (2^12 Hz), so the data cannot capture frequency content above the Nyquist frequency = fs/2 = 2048 Hz. That's OK, because our events only have detectable frequency content in the range given by fband, defined above; the upper end will (almost) always be below the Nyquist frequency. We set f_max = 2000, a bit below Nyquist.\n",
"\n",
"You can see strong spectral lines in the data; they are all of instrumental origin. Some are engineered into the detectors (mirror suspension resonances at ~500 Hz and harmonics, calibration lines, control dither lines, etc) and some (60 Hz and harmonics) are unwanted. We'll return to these, later.\n",
"\n",
"You can't see the signal in this plot, since it is relatively weak and less than a second long, while this plot averages over 32 seconds of data. So this plot is entirely dominated by instrumental noise.\n",
"\n",
"The smooth model is hard-coded and tuned by eye; it won't be right for arbitrary times. We will only use it below for things that don't require much accuracy."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Binary Neutron Star (BNS) detection range\n",
"\n",
"A standard metric that LIGO uses to evaluate the sensitivity of our detectors, based on the detector noise ASD, is the BNS range.\n",
"\n",
"This is defined as the distance to which a LIGO detector can register a BNS signal with a signal-to-noise ratio (SNR) of 8, averaged over source direction and orientation.\n",
"\n",
"We take each neutron star in the BNS system to have a mass of 1.4 times the mass of the sun, and negligible spin.\n",
"\n",
"We have found from experience (supported by careful calculations) that detector noise produces false signals with SNRs that fall off exponentially; only above an SNR of around 8 is it possible to identify a signal above the detector noise.\n",
"\n",
"GWs from BNS mergers are like \"standard sirens\"; we know their amplitude at the source from theoretical calculations. The amplitude falls off like 1/r, so their amplitude at the detectors on Earth tells us how far away they are. This is great, because it is hard, in general, to know the distance to astronomical sources.\n",
"\n",
"The amplitude at the source is computed in the post-Newtonian \"quadrupole approximation\". This is valid for the inspiral phase only, and is approximate at best; there is no simple expression for the post-inspiral (merger and ringdown) phase. So this won't work for high-mass binary black holes like GW150914, which have a lot of signal strength in the post-inspiral phase.\n",
"\n",
"But, in order to use them as standard sirens, we need to know the source direction and orientation relative to the detector and its \"quadrupole antenna pattern\" response to such signals. It is a standard (if non-trivial) computation to average over all source directions and orientations; the average amplitude is 1./2.2648 times the maximum value. \n",
"\n",
"This calculation is described in Appendix D of:\n",
"FINDCHIRP: An algorithm for detection of gravitational waves from inspiraling compact binaries\n",
"B. Allen et al., PHYSICAL REVIEW D 85, 122006 (2012) ; http://arxiv.org/abs/gr-qc/0509116\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"BNS_range = 1\n",
"if BNS_range:\n",
" #-- compute the binary neutron star (BNS) detectability range\n",
"\n",
" #-- choose a detector noise power spectrum:\n",
" f = freqs.copy()\n",
" # get frequency step size\n",
" df = f[2]-f[1]\n",
"\n",
" #-- constants\n",
" # speed of light:\n",
" clight = 2.99792458e8 # m/s\n",
" # Newton's gravitational constant\n",
" G = 6.67259e-11 # m^3/kg/s^2 \n",
" # one parsec, popular unit of astronomical distance (around 3.26 light years)\n",
" parsec = 3.08568025e16 # m\n",
" # solar mass\n",
" MSol = 1.989e30 # kg\n",
" # solar mass in seconds (isn't relativity fun?):\n",
" tSol = MSol*G/np.power(clight,3) # s\n",
" # Single-detector SNR for detection above noise background: \n",
" SNRdet = 8.\n",
" # conversion from maximum range (horizon) to average range:\n",
" Favg = 2.2648\n",
" # mass of a typical neutron star, in solar masses:\n",
" mNS = 1.4\n",
"\n",
" # Masses in solar masses\n",
" m1 = m2 = mNS \n",
" mtot = m1+m2 # the total mass\n",
" eta = (m1*m2)/mtot**2 # the symmetric mass ratio\n",
" mchirp = mtot*eta**(3./5.) # the chirp mass (FINDCHIRP, following Eqn 3.1b)\n",
"\n",
" # distance to a fiducial BNS source:\n",
" dist = 1.0 # in Mpc\n",
" Dist = dist * 1.0e6 * parsec /clight # from Mpc to seconds\n",
"\n",
" # We integrate the signal up to the frequency of the \"Innermost stable circular orbit (ISCO)\" \n",
" R_isco = 6. # Orbital separation at ISCO, in geometric units. 6M for PN ISCO; 2.8M for EOB \n",
" # frequency at ISCO (end the chirp here; the merger and ringdown follow) \n",
" f_isco = 1./(np.power(R_isco,1.5)*np.pi*tSol*mtot)\n",
" # minimum frequency (below which, detector noise is too high to register any signal):\n",
" f_min = 20. # Hz\n",
" # select the range of frequencies between f_min and fisco\n",
" fr = np.nonzero(np.logical_and(f > f_min , f < f_isco))\n",
" # get the frequency and spectrum in that range:\n",
" ffr = f[fr]\n",
"\n",
" # In stationary phase approx, this is htilde(f): \n",
" # See FINDCHIRP Eqns 3.4, or 8.4-8.5 \n",
" htilde = (2.*tSol/Dist)*np.power(mchirp,5./6.)*np.sqrt(5./96./np.pi)*(np.pi*tSol)\n",
" htilde *= np.power(np.pi*tSol*ffr,-7./6.)\n",
" htilda2 = htilde**2\n",
"\n",
" # loop over the detectors\n",
" dets = ['H1', 'L1']\n",
" for det in dets:\n",
" if det is 'L1': sspec = Pxx_L1.copy()\n",
" else: sspec = Pxx_H1.copy()\n",
" sspecfr = sspec[fr]\n",
" # compute \"inspiral horizon distance\" for optimally oriented binary; FINDCHIRP Eqn D2:\n",
" D_BNS = np.sqrt(4.*np.sum(htilda2/sspecfr)*df)/SNRdet\n",
" # and the \"inspiral range\", averaged over source direction and orientation:\n",
" R_BNS = D_BNS/Favg\n",
" print(det+' BNS inspiral horizon = {0:.1f} Mpc, BNS inspiral range = {1:.1f} Mpc'.format(D_BNS,R_BNS))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## BBH range is >> BNS range!\n",
"\n",
"NOTE that, since mass is the source of gravity and thus also of gravitational waves, systems with higher masses (such as the binary black hole merger GW150914) are much \"louder\" and can be detected to much higher distances than the BNS range. We'll compute the BBH range, using a template with specific masses, below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Whitening\n",
"\n",
"From the ASD above, we can see that the data are very strongly \"colored\" - noise fluctuations are much larger at low and high frequencies and near spectral lines, reaching a roughly flat (\"white\") minimum in the band around 80 to 300 Hz.\n",
"\n",
"We can \"whiten\" the data (dividing it by the noise amplitude spectrum, in the fourier domain), suppressing the extra noise at low frequencies and at the spectral lines, to better see the weak signals in the most sensitive band.\n",
"\n",
"Whitening is always one of the first steps in astrophysical data analysis (searches, parameter estimation).\n",
"Whitening requires no prior knowledge of spectral lines, etc; only the data are needed.\n",
"\n",
"To get rid of remaining high frequency noise, we will also bandpass the data.\n",
"\n",
"The resulting time series is no longer in units of strain; now in units of \"sigmas\" away from the mean.\n",
"\n",
"We will plot the whitened strain data, along with the signal template, after the matched filtering section, below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# function to whiten data\n",
"def whiten(strain, interp_psd, dt):\n",
" Nt = len(strain)\n",
" freqs = np.fft.rfftfreq(Nt, dt)\n",
"\n",
" # whitening: transform to freq domain, divide by asd, then transform back, \n",
" # taking care to get normalization right.\n",
" hf = np.fft.rfft(strain)\n",
" white_hf = hf / (np.sqrt(interp_psd(freqs) /dt/2.))\n",
" white_ht = np.fft.irfft(white_hf, n=Nt)\n",
" return white_ht\n",
"\n",
"whiten_data = 1\n",
"if whiten_data:\n",
" # now whiten the data from H1 and L1, and the template (use H1 PSD):\n",
" strain_H1_whiten = whiten(strain_H1,psd_H1,dt)\n",
" strain_L1_whiten = whiten(strain_L1,psd_L1,dt)\n",
" \n",
" # We need to suppress the high frequency noise (no signal!) with some bandpassing:\n",
" bb, ab = butter(4, [fband[0]*2./fs, fband[1]*2./fs], btype='band')\n",
" strain_H1_whitenbp = filtfilt(bb, ab, strain_H1_whiten)\n",
" strain_L1_whitenbp = filtfilt(bb, ab, strain_L1_whiten)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Spectrograms\n",
"\n",
"Now let's plot a short time-frequency spectrogram around our event:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if make_plots:\n",
" # index into the strain time series for this time interval:\n",
" indxt = np.where((time >= tevent-deltat) & (time < tevent+deltat))\n",
"\n",
" # pick a shorter FTT time interval, like 1/8 of a second:\n",
" NFFT = int(fs/8)\n",
" # and with a lot of overlap, to resolve short-time features:\n",
" NOVL = int(NFFT*15./16)\n",
" # and choose a window that minimizes \"spectral leakage\" \n",
" # (https://en.wikipedia.org/wiki/Spectral_leakage)\n",
" window = np.blackman(NFFT)\n",
"\n",
" # the right colormap is all-important! See:\n",
" # http://matplotlib.org/examples/color/colormaps_reference.html\n",
" # viridis seems to be the best for our purposes, but it's new; if you don't have it, you can settle for ocean.\n",
" #spec_cmap='viridis'\n",
" spec_cmap='ocean'\n",
"\n",
" # Plot the H1 spectrogram:\n",
" plt.figure(figsize=(10,6))\n",
" spec_H1, freqs, bins, im = plt.specgram(strain_H1[indxt], NFFT=NFFT, Fs=fs, window=window, \n",
" noverlap=NOVL, cmap=spec_cmap, xextent=[-deltat,deltat])\n",
" plt.xlabel('time (s) since '+str(tevent))\n",
" plt.ylabel('Frequency (Hz)')\n",
" plt.colorbar()\n",
" plt.axis([-deltat, deltat, 0, 2000])\n",
" plt.title('aLIGO H1 strain data near '+eventname)\n",
" plt.savefig(eventname+'_H1_spectrogram.'+plottype)\n",
"\n",
" # Plot the L1 spectrogram:\n",
" plt.figure(figsize=(10,6))\n",
" spec_H1, freqs, bins, im = plt.specgram(strain_L1[indxt], NFFT=NFFT, Fs=fs, window=window, \n",
" noverlap=NOVL, cmap=spec_cmap, xextent=[-deltat,deltat])\n",
" plt.xlabel('time (s) since '+str(tevent))\n",
" plt.ylabel('Frequency (Hz)')\n",
" plt.colorbar()\n",
" plt.axis([-deltat, deltat, 0, 2000])\n",
" plt.title('aLIGO L1 strain data near '+eventname)\n",
" plt.savefig(eventname+'_L1_spectrogram.'+plottype)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above spectrograms, you may see lots of excess power below ~20 Hz, as well as strong spectral lines at 500, 1000, 1500 Hz (also evident in the ASDs above). The lines at multiples of 500 Hz are the harmonics of the \"violin modes\" of the fibers holding up the mirrors of the Advanced LIGO interferometers.\n",
"\n",
"Now let's zoom in on where we think the signal is, using the whitened data, in the hope of seeing a chirp:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if make_plots:\n",
" # plot the whitened data, zooming in on the signal region:\n",
"\n",
" # pick a shorter FTT time interval, like 1/16 of a second:\n",
" NFFT = int(fs/16.0)\n",
" # and with a lot of overlap, to resolve short-time features:\n",
" NOVL = int(NFFT*15/16.0)\n",
" # choose a window that minimizes \"spectral leakage\" \n",
" # (https://en.wikipedia.org/wiki/Spectral_leakage)\n",
" window = np.blackman(NFFT)\n",
"\n",
" # Plot the H1 whitened spectrogram around the signal\n",
" plt.figure(figsize=(10,6))\n",
" spec_H1, freqs, bins, im = plt.specgram(strain_H1_whiten[indxt], NFFT=NFFT, Fs=fs, window=window, \n",
" noverlap=NOVL, cmap=spec_cmap, xextent=[-deltat,deltat])\n",
" plt.xlabel('time (s) since '+str(tevent))\n",
" plt.ylabel('Frequency (Hz)')\n",
" plt.colorbar()\n",
" plt.axis([-0.5, 0.5, 0, 500])\n",
" plt.title('aLIGO H1 strain data near '+eventname)\n",
" plt.savefig(eventname+'_H1_spectrogram_whitened.'+plottype)\n",
"\n",
" # Plot the L1 whitened spectrogram around the signal\n",
" plt.figure(figsize=(10,6))\n",
" spec_H1, freqs, bins, im = plt.specgram(strain_L1_whiten[indxt], NFFT=NFFT, Fs=fs, window=window, \n",
" noverlap=NOVL, cmap=spec_cmap, xextent=[-deltat,deltat])\n",
" plt.xlabel('time (s) since '+str(tevent))\n",
" plt.ylabel('Frequency (Hz)')\n",
" plt.colorbar()\n",
" plt.axis([-0.5, 0.5, 0, 500])\n",
" plt.title('aLIGO L1 strain data near '+eventname)\n",
" plt.savefig(eventname+'_L1_spectrogram_whitened.'+plottype)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Loud (high SNR) signals may be visible in these spectrograms. Compact object mergers show a characteristic \"chirp\" as the signal rises in frequency. If you can't see anything, try\n",
"event GW150914, by changing the "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Waveform Template\n",
"\n",
"The results of a full LIGO-Virgo analysis of this BBH event include a set of parameters that are consistent with a range of parameterized waveform templates. Here we pick one for use in matched filtering. \n",
"\n",
"As noted above, the results won't be identical to what is in the LIGO-Virgo papers, since we're skipping many subtleties, such as combining many consistent templates."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# read in the template (plus and cross) and parameters for the theoretical waveform\n",
"try:\n",
" f_template = h5py.File(fn_template, \"r\")\n",
"except:\n",
" print(\"Cannot find template file!\")\n",
" print(\"You can download it from https://losc.ligo.org/s/events/\"+eventname+'/'+fn_template)\n",
" print(\"Quitting.\")\n",
" quit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# extract metadata from the template file:\n",
"template_p, template_c = f_template[\"template\"][...]\n",
"t_m1 = f_template[\"/meta\"].attrs['m1']\n",
"t_m2 = f_template[\"/meta\"].attrs['m2']\n",
"t_a1 = f_template[\"/meta\"].attrs['a1']\n",
"t_a2 = f_template[\"/meta\"].attrs['a2']\n",
"t_approx = f_template[\"/meta\"].attrs['approx']\n",
"f_template.close()\n",
"# the template extends to roughly 16s, zero-padded to the 32s data length. The merger will be roughly 16s in.\n",
"template_offset = 16.\n",
"\n",
"# whiten the templates:\n",
"template_p_whiten = whiten(template_p,psd_H1,dt)\n",
"template_c_whiten = whiten(template_c,psd_H1,dt)\n",
"template_p_whitenbp = filtfilt(bb, ab, template_p_whiten)\n",
"template_c_whitenbp = filtfilt(bb, ab, template_c_whiten)\n",
"\n",
"# Compute, print and plot some properties of the template:\n",
"\n",
"# constants:\n",
"clight = 2.99792458e8 # m/s\n",
"G = 6.67259e-11 # m^3/kg/s^2 \n",
"MSol = 1.989e30 # kg\n",
"\n",
"# template parameters: masses in units of MSol:\n",
"t_mtot = t_m1+t_m2\n",
"# final BH mass is typically 95% of the total initial mass:\n",
"t_mfin = t_mtot*0.95\n",
"# Final BH radius, in km:\n",
"R_fin = 2*G*t_mfin*MSol/clight**2/1000.\n",
"\n",
"# complex template:\n",
"template = (template_p + template_c*1.j) \n",
"ttime = time-time[0]-template_offset\n",
"\n",
"# compute the instantaneous frequency of this chirp-like signal:\n",
"tphase = np.unwrap(np.angle(template))\n",
"fGW = np.gradient(tphase)*fs/(2.*np.pi)\n",
"# fix discontinuities at the very end:\n",
"iffix = np.where(np.abs(np.gradient(fGW)) > 100.)[0]\n",
"fGW[iffix] = fGW[iffix[0]-1]\n",
"fGW[np.where(fGW < 1.)] = fGW[iffix[0]-1]\n",
"\n",
"# compute v/c:\n",
"voverc = (G*t_mtot*MSol*np.pi*fGW/clight**3)**(1./3.)\n",
"\n",
"# index where f_GW is in-band:\n",
"f_inband = fband[0]\n",
"iband = np.where(fGW > f_inband)[0][0]\n",
"# index at the peak of the waveform:\n",
"ipeak = np.argmax(np.abs(template))\n",
"\n",
"# number of cycles between inband and peak:\n",
"Ncycles = (tphase[ipeak]-tphase[iband])/(2.*np.pi)\n",
"\n",
"print('Properties of waveform template in {0}'.format(fn_template))\n",
"print(\"Waveform family = {0}\".format(t_approx))\n",
"print(\"Masses = {0:.2f}, {1:.2f} Msun\".format(t_m1,t_m2))\n",
"print('Mtot = {0:.2f} Msun, mfinal = {1:.2f} Msun '.format(t_mtot,t_mfin))\n",
"print(\"Spins = {0:.2f}, {1:.2f}\".format(t_a1,t_a2))\n",
"print('Freq at inband, peak = {0:.2f}, {1:.2f} Hz'.format(fGW[iband],fGW[ipeak]))\n",
"print('Time at inband, peak = {0:.2f}, {1:.2f} s'.format(ttime[iband],ttime[ipeak]))\n",
"print('Duration (s) inband-peak = {0:.2f} s'.format(ttime[ipeak]-ttime[iband]))\n",
"print('N_cycles inband-peak = {0:.0f}'.format(Ncycles))\n",
"print('v/c at peak = {0:.2f}'.format(voverc[ipeak]))\n",
"print('Radius of final BH = {0:.0f} km'.format(R_fin))\n",
"\n",
"if make_plots:\n",
" plt.figure(figsize=(10,16))\n",
" plt.subplot(4,1,1)\n",
" plt.plot(time-time[0]-template_offset,template_p)\n",
" plt.xlim([-template_offset,1.])\n",
" plt.grid()\n",
" plt.xlabel('time (s)')\n",
" plt.ylabel('strain')\n",
" plt.title(eventname+' template at D_eff = 1 Mpc')\n",
" \n",
" plt.subplot(4,1,2)\n",
" plt.plot(ttime,template_p)\n",
" plt.xlim([-1.1,0.1])\n",
" plt.grid()\n",
" plt.xlabel('time (s)')\n",
" plt.ylabel('strain')\n",
" #plt.title(eventname+' template at D_eff = 1 Mpc')\n",
" \n",
" plt.subplot(4,1,3)\n",
" plt.plot(ttime,fGW)\n",
" plt.xlim([-1.1,0.1])\n",
" plt.grid()\n",
" plt.xlabel('time (s)')\n",
" plt.ylabel('f_GW')\n",
" #plt.title(eventname+' template f_GW')\n",
" \n",
" plt.subplot(4,1,4)\n",
" plt.plot(ttime,voverc)\n",
" plt.xlim([-1.1,0.1])\n",
" plt.grid()\n",
" plt.xlabel('time (s)')\n",
" plt.ylabel('v/c')\n",
" #plt.title(eventname+' template v/c')\n",
" plt.savefig(eventname+'_template.'+plottype)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Matched filtering to find the signal\n",
"\n",
"Matched filtering is the optimal way to find a known signal buried in stationary, Gaussian noise. It is the standard technique used by the gravitational wave community to find GW signals from compact binary mergers in noisy detector data.\n",
"\n",
"For some loud signals, it may be possible to see the signal in the whitened data or spectrograms. On the other hand, low signal-to-noise ratio (SNR) signals or signals which are of long duration in time may not be visible, even in the whitened data. LIGO scientists use matched filtering to find such \"hidden\" signals. A matched filter works by compressing the entire signal into one time bin (by convention, the \"end time\" of the waveform).\n",
"\n",
"LIGO uses a rather elaborate software suite to match the data against a family of such signal waveforms (\"templates\"), to find the best match. This procedure helps to \"optimally\" separate signals from instrumental noise, and to infer the parameters of the source (masses, spins, sky location, orbit orientation, etc) from the best match templates. \n",
"\n",
"A blind search requires us to search over many compact binary merger templates (eg, 250,000) with different masses and spins, as well as over all times in all detectors, and then requiring triggers coincident in time and template between detectors. It's an extremely complex and computationally-intensive \"search pipeline\".\n",
"\n",
"Here, we simplify things, using only one template (the one identified in the full search as being a good match to the data). \n",
"\n",
"Assuming that the data around this event is fairly Gaussian and stationary, we'll use this simple method to identify the signal (matching the template) in our 32 second stretch of data. The peak in the SNR vs time is a \"single-detector event trigger\".\n",
"\n",
"This calculation is described in section IV of:\n",
"FINDCHIRP: An algorithm for detection of gravitational waves from inspiraling compact binaries\n",
"B. Allen et al., PHYSICAL REVIEW D 85, 122006 (2012) ; http://arxiv.org/abs/gr-qc/0509116\n",
"\n",
"The full search procedure is described in\n",
"GW150914: First results from the search for binary black hole coalescence with Advanced LIGO,\n",
"The LIGO Scientific Collaboration, the Virgo Collaboration, http://arxiv.org/abs/1602.03839"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"scrolled": false
},
"outputs": [],
"source": [
"# -- To calculate the PSD of the data, choose an overlap and a window (common to all detectors)\n",
"# that minimizes \"spectral leakage\" https://en.wikipedia.org/wiki/Spectral_leakage\n",
"NFFT = 4*fs\n",
"psd_window = np.blackman(NFFT)\n",
"# and a 50% overlap:\n",
"NOVL = NFFT/2\n",
"\n",
"# define the complex template, common to both detectors:\n",
"template = (template_p + template_c*1.j) \n",
"# We will record the time where the data match the END of the template.\n",
"etime = time+template_offset\n",
"# the length and sampling rate of the template MUST match that of the data.\n",
"datafreq = np.fft.fftfreq(template.size)*fs\n",
"df = np.abs(datafreq[1] - datafreq[0])\n",
"\n",
"# to remove effects at the beginning and end of the data stretch, window the data\n",
"# https://en.wikipedia.org/wiki/Window_function#Tukey_window\n",
"try: dwindow = signal.tukey(template.size, alpha=1./8) # Tukey window preferred, but requires recent scipy version \n",
"except: dwindow = signal.blackman(template.size) # Blackman window OK if Tukey is not available\n",
"\n",
"# prepare the template fft.\n",
"template_fft = np.fft.fft(template*dwindow) / fs\n",
"\n",
"# loop over the detectors\n",
"dets = ['H1', 'L1']\n",
"for det in dets:\n",
"\n",
" if det is 'L1': data = strain_L1.copy()\n",
" else: data = strain_H1.copy()\n",
"\n",
" # -- Calculate the PSD of the data. Also use an overlap, and window:\n",
" data_psd, freqs = mlab.psd(data, Fs = fs, NFFT = NFFT, window=psd_window, noverlap=NOVL)\n",
"\n",
" # Take the Fourier Transform (FFT) of the data and the template (with dwindow)\n",
" data_fft = np.fft.fft(data*dwindow) / fs\n",
"\n",
" # -- Interpolate to get the PSD values at the needed frequencies\n",
" power_vec = np.interp(np.abs(datafreq), freqs, data_psd)\n",
"\n",
" # -- Calculate the matched filter output in the time domain:\n",
" # Multiply the Fourier Space template and data, and divide by the noise power in each frequency bin.\n",
" # Taking the Inverse Fourier Transform (IFFT) of the filter output puts it back in the time domain,\n",
" # so the result will be plotted as a function of time off-set between the template and the data:\n",
" optimal = data_fft * template_fft.conjugate() / power_vec\n",
" optimal_time = 2*np.fft.ifft(optimal)*fs\n",
"\n",
" # -- Normalize the matched filter output:\n",
" # Normalize the matched filter output so that we expect a value of 1 at times of just noise.\n",
" # Then, the peak of the matched filter output will tell us the signal-to-noise ratio (SNR) of the signal.\n",
" sigmasq = 1*(template_fft * template_fft.conjugate() / power_vec).sum() * df\n",
" sigma = np.sqrt(np.abs(sigmasq))\n",
" SNR_complex = optimal_time/sigma\n",
"\n",
" # shift the SNR vector by the template length so that the peak is at the END of the template\n",
" peaksample = int(data.size / 2) # location of peak in the template\n",
" SNR_complex = np.roll(SNR_complex,peaksample)\n",
" SNR = abs(SNR_complex)\n",
"\n",
" # find the time and SNR value at maximum:\n",
" indmax = np.argmax(SNR)\n",
" timemax = time[indmax]\n",
" SNRmax = SNR[indmax]\n",
"\n",
" # Calculate the \"effective distance\" (see FINDCHIRP paper for definition)\n",
" # d_eff = (8. / SNRmax)*D_thresh\n",
" d_eff = sigma / SNRmax\n",
" # -- Calculate optimal horizon distnace\n",
" horizon = sigma/8\n",
"\n",
" # Extract time offset and phase at peak\n",
" phase = np.angle(SNR_complex[indmax])\n",
" offset = (indmax-peaksample)\n",
" #print offset\n",
"\n",
" # apply time offset, phase, and d_eff to whitened template, for plotting\n",
" template_whitened = (template_p_whitenbp + template_c_whitenbp*1.j) \n",
" template_phaseshifted = np.real(template_whitened*np.exp(1j*phase))\n",
" template_match = np.roll(template_phaseshifted,offset) / d_eff\n",
"\n",
" print('For detector {0}, maximum at {1:.4f} with SNR = {2:.1f}, D_eff = {3:.2f}, horizon = {4:0.1f} Mpc' \n",
" .format(det,timemax,SNRmax,d_eff,horizon))\n",
"\n",
" if make_plots:\n",
"\n",
" # plotting changes for the detectors:\n",
" if det is 'L1': \n",
" pcolor='g'\n",
" strain_whitenbp = strain_L1_whitenbp\n",
" else:\n",
" pcolor='r'\n",
" strain_whitenbp = strain_H1_whitenbp\n",
"\n",
" # -- Plot the result\n",
" plt.figure(figsize=(10,8))\n",
" plt.subplot(2,1,1)\n",
" plt.plot(time-timemax, SNR, pcolor,label=det+' SNR(t)')\n",
" #plt.ylim([0,25.])\n",
" plt.grid('on')\n",
" plt.ylabel('SNR')\n",
" plt.xlabel('Time since {0:.4f}'.format(timemax))\n",
" plt.legend(loc='upper left')\n",
" plt.title(det+' matched filter SNR around event')\n",
"\n",
" # zoom in\n",
" plt.subplot(2,1,2)\n",
" plt.plot(time-timemax, SNR, pcolor,label=det+' SNR(t)')\n",
" plt.grid('on')\n",
" plt.ylabel('SNR')\n",
" plt.xlim([-0.15,0.05])\n",
" #plt.xlim([-0.3,+0.3])\n",
" plt.grid('on')\n",
" plt.xlabel('Time since {0:.4f}'.format(timemax))\n",
" plt.legend(loc='upper left')\n",
" plt.savefig(eventname+\"_\"+det+\"_SNR.\"+plottype)\n",
"\n",
" plt.figure(figsize=(10,8))\n",
" plt.subplot(2,1,1)\n",
" plt.plot(time-tevent,strain_whitenbp,pcolor,label=det+' whitened h(t)')\n",
" plt.plot(time-tevent,template_match,'k',label='Template(t)')\n",
" plt.ylim([-3,3])\n",
" plt.xlim([-0.15,0.05])\n",
" plt.grid('on')\n",
" plt.xlabel('Time since {0:.4f}'.format(timemax))\n",
" plt.ylabel('whitened strain (units of noise stdev)')\n",
" plt.legend(loc='upper left')\n",
" plt.title(det+' whitened data around event')\n",
"\n",
" plt.subplot(2,1,2)\n",
" plt.plot(time-tevent,strain_whitenbp-template_match,pcolor,label=det+' resid')\n",
" plt.ylim([-3,3])\n",
" plt.xlim([-0.15,0.05])\n",
" plt.grid('on')\n",
" plt.xlabel('Time since {0:.4f}'.format(timemax))\n",
" plt.ylabel('whitened strain (units of noise stdev)')\n",
" plt.legend(loc='upper left')\n",
" plt.title(det+' Residual whitened data after subtracting template around event')\n",
" plt.savefig(eventname+\"_\"+det+\"_matchtime.\"+plottype)\n",
" \n",
" # -- Display PSD and template\n",
" # must multiply by sqrt(f) to plot template fft on top of ASD:\n",
" plt.figure(figsize=(10,6))\n",
" template_f = np.absolute(template_fft)*np.sqrt(np.abs(datafreq)) / d_eff\n",
" plt.loglog(datafreq, template_f, 'k', label='template(f)*sqrt(f)')\n",
" plt.loglog(freqs, np.sqrt(data_psd),pcolor, label=det+' ASD')\n",
" plt.xlim(20, fs/2)\n",
" plt.ylim(1e-24, 1e-20)\n",
" plt.grid()\n",
" plt.xlabel('frequency (Hz)')\n",
" plt.ylabel('strain noise ASD (strain/rtHz), template h(f)*rt(f)')\n",
" plt.legend(loc='upper left')\n",
" plt.title(det+' ASD and template around event')\n",
" plt.savefig(eventname+\"_\"+det+\"_matchfreq.\"+plottype)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Notes on these results\n",
"\n",
"* We make use of only one template, with a simple ASD estimate. The full analysis produces a Bayesian posterior result using many nearby templates. It does a more careful job estimating the ASD, and includes effects of uncertain calibration. \n",
"* As a result, our parameters (SNR, masses, spins, D_eff) are somewhat different from what you will see in our papers.\n",
"* We compute an \"effective distance\" D_eff. Is is NOT an estimate of the actual (luminosity) distance, which depends also on the source location and orbit orientation.\n",
"* These distances are at non-zero redshift, so cosmological effects must be taken into account (neglected here). Since we estimate the BH masses using the phase evolution of the waveform, which has been redshifted, our masses are themselves \"redshifted\". The true source masses must be corrected for this effect; they are smaller by a factor (1+z).\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Make sound files\n",
"\n",
"Make wav (sound) files from the filtered, downsampled data, +-2s around the event."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# make wav (sound) files from the whitened data, +-2s around the event.\n",
"\n",
"from scipy.io import wavfile\n",
"\n",
"# function to keep the data within integer limits, and write to wavfile:\n",
"def write_wavfile(filename,fs,data):\n",
" d = np.int16(data/np.max(np.abs(data)) * 32767 * 0.9)\n",
" wavfile.write(filename,int(fs), d)\n",
"\n",
"deltat_sound = 2. # seconds around the event\n",
"\n",
"# index into the strain time series for this time interval:\n",
"indxd = np.where((time >= tevent-deltat_sound) & (time < tevent+deltat_sound))\n",
"\n",
"# write the files:\n",
"write_wavfile(eventname+\"_H1_whitenbp.wav\",int(fs), strain_H1_whitenbp[indxd])\n",
"write_wavfile(eventname+\"_L1_whitenbp.wav\",int(fs), strain_L1_whitenbp[indxd])\n",
"\n",
"# re-whiten the template using the smoothed PSD; it sounds better!\n",
"template_p_smooth = whiten(template_p,psd_smooth,dt)\n",
"\n",
"# and the template, sooming in on [-3,+1] seconds around the merger:\n",
"indxt = np.where((time >= (time[0]+template_offset-deltat_sound)) & (time < (time[0]+template_offset+deltat_sound)))\n",
"write_wavfile(eventname+\"_template_whiten.wav\",int(fs), template_p_smooth[indxt])\n",
"#plt.plot(template_p_smooth[indxt])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With good headphones, you may be able to hear a faint thump in the middle; that's our signal!\n",
"\n",
"We can enhance this by increasing the frequency; \n",
"this is the \"audio\" equivalent of the enhanced visuals that NASA employs on telescope images with \"false color\".\n",
"\n",
"The code below will shift the data up by 400 Hz (by taking an FFT, shifting/rolling the frequency series, then inverse fft-ing). The resulting sound file will be noticibly more high-pitched, and the signal will be easier to hear."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# function that shifts frequency of a band-passed signal\n",
"def reqshift(data,fshift=100,sample_rate=4096):\n",
" \"\"\"Frequency shift the signal by constant\n",
" \"\"\"\n",
" x = np.fft.rfft(data)\n",
" T = len(data)/float(sample_rate)\n",
" df = 1.0/T\n",
" nbins = int(fshift/df)\n",
" # print T,df,nbins,x.real.shape\n",
" y = np.roll(x.real,nbins) + 1j*np.roll(x.imag,nbins)\n",
" y[0:nbins]=0.\n",
" z = np.fft.irfft(y)\n",
" return z\n",
"\n",
"# parameters for frequency shift\n",
"fs = 4096\n",
"fshift = 400.\n",
"speedup = 1.\n",
"fss = int(float(fs)*float(speedup))\n",
"\n",
"# shift frequency of the data\n",
"strain_H1_shifted = reqshift(strain_H1_whitenbp,fshift=fshift,sample_rate=fs)\n",
"strain_L1_shifted = reqshift(strain_L1_whitenbp,fshift=fshift,sample_rate=fs)\n",
"\n",
"# write the files:\n",
"write_wavfile(eventname+\"_H1_shifted.wav\",int(fs), strain_H1_shifted[indxd])\n",
"write_wavfile(eventname+\"_L1_shifted.wav\",int(fs), strain_L1_shifted[indxd])\n",
"\n",
"# and the template:\n",
"template_p_shifted = reqshift(template_p_smooth,fshift=fshift,sample_rate=fs)\n",
"write_wavfile(eventname+\"_template_shifted.wav\",int(fs), template_p_shifted[indxt])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Listen to the frequency-shifted template"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fna = eventname+\"_template_shifted.wav\"\n",
"print(fna)\n",
"from IPython.display import Audio\n",
"Audio(fna)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data segments\n",
"\n",
"As mentioned above, LIGO strain time series data has gaps (filled with NaNs) when the detectors are not taking valid (\"science quality\") data. Analyzing these data requires the user to loop over \"segments\" of valid data stretches. For details, see the notes on segments or introduction to LIGO data files.\n",
"\n",
"In the code below, we can check times around this event for gaps in the L1 data. You are welcome to repeat this with H1 data, with files containing 4096 seconds of data, and with data sampled at 16384 Hz. All of the relevant files can be downloaded from LOSC event pages.\n",
"\n",
"We also unpack the DQ and HW injection bits to check what their values are."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"data_segments = 1\n",
"if data_segments:\n",
" # read in the data at 4096 Hz:\n",
" # fn = 'L-L1_LOSC_4_V1-1126259446-32.hdf5'\n",
" strain, time, chan_dict = rl.loaddata(fn_L1, 'H1')\n",
"\n",
" print(\"Contents of all the key, value pairs in chan_dict\")\n",
" for keys,values in chan_dict.items():\n",
" print(keys)\n",
" print(values)\n",
"\n",
" print('Total number of non-NaNs in these data = ',np.sum(~np.isnan(strain)))\n",
" print('GPS start, GPS stop and length of all data in this file = ',time[0], time[-1],len(strain))\n",
"\n",
" # select the level of data quality; default is \"DATA\" but \"CBC_CAT3\" is a conservative choice:\n",
" DQflag = 'CBC_CAT3'\n",
" # readligo.py method for computing segments (start and stop times with continuous valid data):\n",
" segment_list = rl.dq_channel_to_seglist(chan_dict[DQflag])\n",
" print('Number of segments with DQflag',DQflag,' = ',len(segment_list))\n",
"\n",
" # loop over seconds and print out start, stop and length:\n",
" iseg = 0\n",
" for segment in segment_list:\n",
" time_seg = time[segment]\n",
" seg_strain = strain[segment]\n",
" print('GPS start, GPS stop and length of segment',iseg, \\\n",
" 'in this file = ',time_seg[0], time_seg[-1], len(seg_strain))\n",
" iseg = iseg+1\n",
" # here is where you would insert code to analyze the data in this segment.\n",
"\n",
" # now look at segments with no CBC hardware injections:\n",
" DQflag = 'NO_CBC_HW_INJ'\n",
" segment_list = rl.dq_channel_to_seglist(chan_dict['NO_CBC_HW_INJ'])\n",
" print('Number of segments with DQflag',DQflag,' = ',len(segment_list))\n",
" iseg = 0\n",
" for segment in segment_list:\n",
" time_seg = time[segment]\n",
" seg_strain = strain[segment]\n",
" print('GPS start, GPS stop and length of segment',iseg, \\\n",
" 'in this file = ',time_seg[0], time_seg[-1], len(seg_strain))\n",
" iseg = iseg+1\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comments on sampling rate\n",
"\n",
"LIGO data are acquired at 16384 Hz (2^14 Hz). Here, we have been working with data downsampled to 4096 Hz, to save on download time, disk space, and memory requirements. \n",
"\n",
"This is entirely sufficient for signals with no frequency content above f_Nyquist = fs/2 = 2048 Hz, such as signals from higher-mass binary black hole systems; the frequency at which the merger begins (at the innermost stable circular orbit) for equal-mass, spinless black holes is roughly 1557 Hz * (2.8/M_tot), where 2.8 solar masses is the total mass of a canonical binary neutron star system. \n",
"\n",
"If, however, you are interested in signals with frequency content above 2048 Hz, you need the data sampled at the full rate of 16384 Hz. \n",
"\n",
"In the tutorial for GW150914: https://losc.ligo.org/s/events/GW150914/GW150914_tutorial.html\n",
"we demonstrate how to get the data at the full 16384 Hz sampling rate, do the downsampling, and show how it might limit you if you are interested in frequency content near 2048 Hz and above."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.11"
}
},
"nbformat": 4,
"nbformat_minor": 0
}