{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "<div style='background-image: url(\"../images/header.svg\") ; padding: 0px ; background-size: cover ; border-radius: 5px ; height: 250px'>\n",
    "    <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.7) ; width: 50% ; height: 150px\">\n",
    "        <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n",
    "            <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.8) ; line-height: 100%\">Signal Processing</div>\n",
    "            <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.5)\">Filtering Basics - Solution</div>\n",
    "        </div>\n",
    "    </div>\n",
    "</div>\n",
    "\n",
    "Seismo-Live: http://seismo-live.org\n",
    "\n",
    "##### Authors:\n",
    "* Stefanie Donner ([@stefdonner](https://github.com/stefdonner))\n",
    "* Celine Hadziioannou ([@hadzii](https://github.com/hadzii))\n",
    "* Ceri Nunn ([@cerinunn](https://github.com/cerinunn))\n",
    "\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 0 - Preparation: load packages, set some basic options  \n",
    "#%matplotlib inline\n",
    "from obspy import *\n",
    "from obspy.clients.fdsn import Client\n",
    "import numpy as np\n",
    "import matplotlib.pylab as plt\n",
    "plt.style.use('ggplot')\n",
    "plt.rcParams['figure.figsize'] = 15, 4\n",
    "plt.rcParams['lines.linewidth'] = 0.5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Basics in filtering"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## The Filter\n",
    "\n",
    "In seismology, filters are used to correct for the instrument response, avoid aliasing effects, separate 'wanted' from 'unwanted' frequencies, identify harmonic signals, model a specific recording instrument, and much more ...\n",
    "\n",
    "There is no clear classification of filters. Roughly speaking, we can distinguish linear vs. non-linear, analog (circuits, resistors, conductors) vs. digital (logical components), and continuous vs. discrete filters. In seismology, we generally avoid non-linear filters, because their output contains frequencies which are not in the input signal. Analog filters can be continuous or discrete, while digital filters are always discrete. Discrete filters can be subdivided into infinite impulse response (IIR) filters, which are recursive and causal, and finite impulse response (FIR) filters, which are non-recursive and causal or acausal. We will explain more about these types of filters below.\n",
    "Some filters have a special name, such as Butterworth, Chebyshev or Bessel filters, but they can also be integrated in the classification described above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Response Funtion\n",
    "\n",
    "A filter is characterised by its frequency response function $T(j\\omega)$ which relate the Fourier transformation of the output signal $Y(j\\omega)$ and the Fourier transformation of the input signal $X(j\\omega)$:\n",
    "$$ Y(j\\omega) = T(j\\omega)X(j\\omega)$$\n",
    "\n",
    "For a simple lowpass filter it is given as:\n",
    "$$ |T(j\\omega)| = \\sqrt{ \\frac{1}{1+(\\frac{\\omega}{\\omega_c})^{2n}} } $$\n",
    "\n",
    "with $\\omega$ indicating the frequency samples, $\\omega_c$ the corner frequency of the filter, and $n$ the order of the filter (also called the number of corners of the filter). For a lowpass filter, all frequencies lower than the corner frequency are allowed to pass the filter. This is the pass band of the filter. On the other hand, the range of frequencies above the corner frequency is called stop band. In between lies the transition band, a small band of frequencies in which the passed amplitudes are gradually decreased to zero. The steepness of the slope of this transition band is defined by the order of the filter: the higher the order, the steeper the slope, the more effectively 'unwanted' frequencies get removed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Time Domain vs. Frequency Domain\n",
    "\n",
    "In the time domain, filtering means to convolve the data with the impulse response function of the filter. Doing this operation in the time domain is mathematically complex, computationally expensive and slow. Therefore, the digital application of filters is almost always done in the frequency domain, where it simplifies to a much faster multiplication between data and filter response. The procedure is as follows: transfer the signal into the frequency domain via FFT, multiply it with the filter's frequency response function (i.e. the FFT of the impulse response function), and transfer the result back to the time-domain. As a consequence, when filtering, we have to be aware of the characteristics and pit-falls of the Fourier transformation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Filter types\n",
    "\n",
    "There are 4 main types of filters: a lowpass, a highpass, a bandpass, and a bandstop filter. Low- and highpass filters only have one corner frequency, allowing frequencies below and above this corner frequency to pass the filter, respectively. In contrast, bandpass and bandstop filters have two corner frequencies, defining a frequency band to pass and to stop, respectively.\n",
    "Here, we want to see how exactly these filters act on the input signal. In Cell 1, the vertical component of the M$_w\\,$9.1 Tohoku earthquake, recorded at Bochum - Germany, is downloaded and pre-processed. In Cell 2, the four basic filters are applied to these data and plotted together with the filter functions and the resulting amplitude spectrum.\n",
    "\n",
    "1) Look at the figure and explain what the different filters do.\n",
    "\n",
    "2) Change the order of the filter (i.e the number of corners). What happens and why?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 1: prepare data from Tohoku-Oki earthquake. \n",
    "client = Client(\"BGR\")\n",
    "t1 = UTCDateTime(\"2011-03-11T05:00:00.000\")\n",
    "st = client.get_waveforms(\"GR\", \"BUG\", \"\", \"LHZ\", t1, t1 + 6 * 60 * 60, \n",
    "                          attach_response = True)\n",
    "st.remove_response(output=\"VEL\")\n",
    "st.detrend('linear')\n",
    "st.detrend('demean')\n",
    "st[0].plot();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 1b: print stats\n",
    "print(st[0].stats)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 2 - filter types\n",
    "npts = st[0].stats.npts                   # number of samples in the trace\n",
    "dt = st[0].stats.delta                    # sample interval\n",
    "fNy = 1. / (2. * dt)                      # Nyquist frequency \n",
    "time = np.arange(0, npts) * dt            # time axis for plotting\n",
    "freq = np.linspace(0, fNy, npts // 2 + 1) # frequency axis for plotting\n",
    "corners = 4                               # order of filter\n",
    "\n",
    "# several filter frequencies for the different filter types\n",
    "f0 = 0.04\n",
    "fmin1 = 0.04\n",
    "fmax1 = 0.07\n",
    "fmin2 = 0.03\n",
    "fmax2 = 0.07\n",
    "\n",
    "# filter functions\n",
    "LP = 1 / ( 1 + (freq / f0) ** (2 * corners))\n",
    "HP = 1 - 1 / (1 + (freq / f0) ** (2 * corners))\n",
    "wc = fmax1 - fmin1\n",
    "wb = 0.5 * wc + fmin1\n",
    "BP = 1/(1 + ((freq - wb) / wc) ** (2 * corners))\n",
    "wc = fmax2 - fmin2\n",
    "wb = 0.5 * wc + fmin2\n",
    "BS = 1 - ( 1 / (1 + ((freq - wb) / wc) ** (2 * corners)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 2b: filtered traces\n",
    "stHP = st.copy()\n",
    "stHP.filter('highpass', freq=f0, corners=corners, zerophase=True)\n",
    "stLP = st.copy()\n",
    "stLP.filter('lowpass', freq=f0, corners=corners, zerophase=True)\n",
    "stBP = st.copy()\n",
    "stBP.filter('bandpass', freqmin=fmin1, freqmax=fmax1, corners=corners, zerophase=True)\n",
    "stBS = st.copy()\n",
    "stBS.filter('bandstop', freqmin=fmin2, freqmax=fmax2, corners=corners, zerophase=True)\n",
    "\n",
    "# amplitude spectras\n",
    "Ospec = np.fft.rfft(st[0].data)\n",
    "LPspec = np.fft.rfft(stLP[0].data)\n",
    "HPspec = np.fft.rfft(stHP[0].data)\n",
    "BPspec = np.fft.rfft(stBP[0].data)\n",
    "BSspec = np.fft.rfft(stBS[0].data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "rise": {
      "scroll": true
     },
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 2c - plot\n",
    "plt.rcParams['figure.figsize'] = 17, 17\n",
    "tx1 = 3000\n",
    "tx2 = 8000\n",
    "fx2 = 0.12\n",
    "\n",
    "fig = plt.figure()\n",
    "\n",
    "ax1 = fig.add_subplot(5,3,1)\n",
    "ax1.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(time, st[0].data, 'k')\n",
    "plt.xlim(tx1, tx2)\n",
    "plt.title('time-domain data')\n",
    "plt.ylabel('original data \\n amplitude [ms$^-1$]')\n",
    "\n",
    "ax3 = fig.add_subplot(5,3,3)\n",
    "plt.plot(freq, abs(Ospec), 'k')\n",
    "plt.title('frequency-domain data \\n amplitude spectrum')\n",
    "plt.ylabel('amplitude')\n",
    "plt.xlim(0,fx2)\n",
    "\n",
    "ax4 = fig.add_subplot(5,3,4)\n",
    "ax4.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(time, stLP[0].data, 'k')\n",
    "plt.xlim(tx1, tx2)\n",
    "plt.ylabel('LOWPASS  \\n amplitude [ms$^-1$]')\n",
    "\n",
    "ax5 = fig.add_subplot(5,3,5)\n",
    "plt.plot(freq, LP, 'k', linewidth=1.5)\n",
    "plt.xlim(0,fx2)\n",
    "plt.ylim(-0.1,1.1)\n",
    "plt.title('filter function')\n",
    "plt.ylabel('amplitude [%]')\n",
    "\n",
    "ax6 = fig.add_subplot(5,3,6)\n",
    "plt.plot(freq, abs(LPspec), 'k')\n",
    "plt.ylabel('amplitude ')\n",
    "plt.xlim(0,fx2)\n",
    "\n",
    "ax7 = fig.add_subplot(5,3,7)\n",
    "ax7.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(time, stHP[0].data, 'k')\n",
    "plt.xlim(tx1, tx2)\n",
    "plt.ylabel('HIGHPASS  \\n amplitude [ms$^-1$]')\n",
    "\n",
    "ax8 = fig.add_subplot(5,3,8)\n",
    "plt.plot(freq, HP, 'k', linewidth=1.5)\n",
    "plt.xlim(0,fx2)\n",
    "plt.ylim(-0.1,1.1)\n",
    "plt.ylabel('amplitude [%]')\n",
    "\n",
    "ax9 = fig.add_subplot(5,3,9)\n",
    "plt.plot(freq, abs(HPspec), 'k')\n",
    "plt.ylabel('amplitude ')\n",
    "plt.xlim(0,fx2)\n",
    "\n",
    "ax10 = fig.add_subplot(5,3,10)\n",
    "ax10.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(time, stBP[0].data, 'k')\n",
    "plt.xlim(tx1, tx2)\n",
    "plt.ylabel('BANDPASS  \\n amplitude [ms$^-1$]')\n",
    "\n",
    "ax11 = fig.add_subplot(5,3,11)\n",
    "plt.plot(freq, BP, 'k', linewidth=1.5)\n",
    "plt.xlim(0,fx2)\n",
    "plt.ylim(-0.1,1.1)\n",
    "plt.ylabel('amplitude [%]')\n",
    "\n",
    "ax12 = fig.add_subplot(5,3,12)\n",
    "plt.plot(freq, abs(BPspec), 'k')\n",
    "plt.ylabel('amplitude ')\n",
    "plt.xlim(0,fx2)\n",
    "\n",
    "ax13 = fig.add_subplot(5,3,13)\n",
    "ax13.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(time, stBS[0].data, 'k')\n",
    "plt.xlim(tx1, tx2)\n",
    "plt.xlabel('time [sec]')\n",
    "plt.ylabel('BANDSTOPP \\n amplitude [ms$^-1$]');\n",
    "\n",
    "ax14 = fig.add_subplot(5,3,14)\n",
    "plt.plot(freq, BS, 'k', linewidth=1.5)\n",
    "plt.xlim(0,fx2)\n",
    "plt.ylim(-0.1,1.1)\n",
    "plt.ylabel('amplitude [%]')\n",
    "plt.xlabel('frequency [Hz]')\n",
    "\n",
    "ax15 = fig.add_subplot(5,3,15)\n",
    "plt.plot(freq, abs(BSspec), 'k')\n",
    "plt.xlabel('frequency [Hz]')\n",
    "plt.ylabel('amplitude ')\n",
    "plt.xlim(0,fx2)\n",
    "\n",
    "plt.subplots_adjust(wspace=0.3, hspace=0.4)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Causal vs. acausal\n",
    "\n",
    "Filters can be causal or acausal. The output of a causal filter depends only on past and present input, while the output also depends on future input. Thus, an acausal filter is always symmetric and a causal one not. In this exercise, we want to see the effects of such filters on the signal. In Cell 3, the example seismogram of ObsPy is loaded and lowpass filtered several times with different filter order $n$ and causality.\n",
    "\n",
    "3) Explain the effects of the different filters. You can also play with the order of the filter (variable $ncorners$).\n",
    "\n",
    "4) Zoom into a small window around the first onset (change the variables $start$, $end$ and $amp$). Which filter would you use for which purpose?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 3 - filter effects\n",
    "stf = read()                   # load example seismogram\n",
    "tr = stf[0]                    # select the first trace in the Stream object\n",
    "tr.detrend('demean')           # preprocess data\n",
    "tr.detrend('linear')\n",
    "tr.filter(\"highpass\", freq=2)  # removing long-period noise\n",
    "print(tr)\n",
    "t = tr.times()                 # time vector for x axis\n",
    "\n",
    "f = 15.0                       # frequency for filters (intial: 10 Hz)\n",
    "start = 4                      # start time to plot in sec (initial: 4)\n",
    "end = 8                        # end time to plot in sec (initial: 8)\n",
    "amp = 1500                     # amplitude range for plotting (initial: 1500)  \n",
    "ncorners = 4                   # number of corners/order of the filter (initial: 4)\n",
    "\n",
    "tr_filt = tr.copy()            # causal filter / not zero phase. Order = 2\n",
    "tr_filt.filter('lowpass', freq=f, zerophase=False, corners=2)\n",
    "tr_filt2 = tr.copy()           # causal filter / not zero phase. Order = set by ncorners\n",
    "tr_filt2.filter('lowpass', freq=f, zerophase=False, corners=ncorners)\n",
    "tr_filt3 = tr.copy()           # acausal filter / zero phase. Order = set by ncorners\n",
    "tr_filt3.filter('lowpass', freq=f, zerophase=True, corners=ncorners)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 3b: plot - comment single lines to better see the remaining ones\n",
    "plt.rcParams['figure.figsize'] = 15, 4\n",
    "plt.plot(t, tr.data, 'k', label='original', linewidth=1.)\n",
    "plt.plot(t, tr_filt.data, 'b', label='causal, n=2', linewidth=1.2)\n",
    "plt.plot(t, tr_filt2.data, 'r', label='causal, n=%s' % ncorners, linewidth=1.2)\n",
    "plt.plot(t, tr_filt3.data, 'g', label='acausal, n=%s' % ncorners, linewidth=1.2)\n",
    "\n",
    "plt.xlabel('time [s]')\n",
    "plt.xlim(start, end)    \n",
    "plt.ylim(-amp, amp)\n",
    "plt.ylabel('amplitude [arbitrary]')\n",
    "plt.legend(loc='lower right')\n",
    "\n",
    "plt.show();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Frequency ranges - bandpass filter\n",
    "\n",
    "We will now look at an event which took place in Kazakhstan on July 8, 1989. We want to see how filtering helps to derive information from a signal. The signal has been recorded by a Chinese station and is bandpassed in several different frequency bands.\n",
    "\n",
    "5) What do you see in the different frequency bands?\n",
    "\n",
    "6) Play with the channel used for filtering in Cell 5. What do you not see? Can you guess what kind of event it is?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 4 - get + preprocess data\n",
    "c = Client(\"IRIS\")\n",
    "tmp1 = UTCDateTime(\"1989-10-19T09:50:00.0\")\n",
    "tmp2 = UTCDateTime(\"1989-10-19T10:20:00.0\")\n",
    "dat = c.get_waveforms(\"CD\", \"WMQ\", \"\", \"BH*\", tmp1, tmp2, attach_response = True)\n",
    "dat.detrend('linear')\n",
    "dat.detrend('demean')\n",
    "dat.remove_response(output=\"VEL\")\n",
    "dat.detrend('linear')\n",
    "dat.detrend('demean')\n",
    "print(dat)\n",
    "dat.plot();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 5 - filter data in different frequency ranges\n",
    "\n",
    "chanel = 2\n",
    "tm = dat[chanel].times()\n",
    "xmin = 0\n",
    "xmax = 700\n",
    "\n",
    "dat1 = dat[chanel].copy()\n",
    "dat2 = dat[chanel].copy()\n",
    "dat2.filter(type=\"bandpass\", freqmin=0.01, freqmax=0.05)\n",
    "dat3 = dat[chanel].copy()\n",
    "dat3.filter(type=\"bandpass\", freqmin=0.05, freqmax=0.1)\n",
    "dat4 = dat[chanel].copy()\n",
    "dat4.filter(type=\"bandpass\", freqmin=0.1, freqmax=0.5)\n",
    "dat5 = dat[chanel].copy()\n",
    "dat5.filter(type=\"bandpass\", freqmin=0.5, freqmax=1)\n",
    "dat6 = dat[chanel].copy()\n",
    "dat6.filter(type=\"bandpass\", freqmin=1., freqmax=5.)\n",
    "dat7 = dat[chanel].copy()\n",
    "dat7.filter(type=\"bandpass\", freqmin=5., freqmax=9.99)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "# Cell 5b: plot\n",
    "plt.rcParams['figure.figsize'] = 17, 21\n",
    "fig = plt.figure()\n",
    "ax1 = fig.add_subplot(7,1,1)\n",
    "ax1.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat1.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('unfiltered')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax2 = fig.add_subplot(7,1,2)\n",
    "ax2.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat2.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('0.01 - 0.05 Hz')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax3 = fig.add_subplot(7,1,3)\n",
    "ax3.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat3.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('0.05 - 0.1 Hz')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax4 = fig.add_subplot(7,1,4)\n",
    "ax4.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat4.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('0.1 - 0.5 Hz')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax5 = fig.add_subplot(7,1,5)\n",
    "ax5.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat5.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('0.5 - 1.0 Hz')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax6 = fig.add_subplot(7,1,6)\n",
    "ax6.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat6.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('1.0 - 5.0 Hz')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "ax7 = fig.add_subplot(7,1,7)\n",
    "ax7.ticklabel_format(style='sci', axis='y', scilimits=(-1,1))\n",
    "plt.plot(tm, dat7.data, 'k')\n",
    "plt.xlim(xmin, xmax)\n",
    "plt.title('5.0 - 10.0 Hz')\n",
    "plt.xlabel('time [sec]')\n",
    "plt.ylabel('amplitude \\n [m/s]')\n",
    "\n",
    "plt.subplots_adjust(hspace=0.3)\n",
    "plt.show();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "source": [
    "# Answers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
   "source": [
    "1) The lowpass removes frequencies below the corner frequency of the filter, while a highpass removes all frequencies above the corner frequency. The bandpass allows all frequencies within the two corner frequencies, while a bandstop allows all frequencies outside this range.\n",
    "In the filtered signals not only the frequency content is changed (see plot of spectrum) but also the maximum amplitudes (see scaling of y-axis in time-domain plot.) In the frequency-domain plot, we see that each frequency contributes with a distinct amount of amplitude to the final signal. Depending on which frequencies remain after filtering, we have altered the amplitudes as well as the frequencies of the filtered signal.\n",
    "Be aware: \"high-\" and \"low-\"pass refers to the unit 'frequency'! When you think in terms of 'period', you have to switch your mind.\n",
    "\n",
    "2) When setting the order of the filter very high, the slopes of the filter functions turn into steps and the amplitude spectra stop abruptly. Due to the harsh steps in the filter functions, we risk Gibbs effects during filtering. However, when setting the order of the filter lower, the slopes become too gentle and the unwanted frequencies are not removed effectively. Thus, we always have to balance between minimizing the Gibbs effects (low order) and maximizing the effective removal of frequencies (high order).\n",
    "\n",
    "3) The difference between the two causal filters (red and blue) are minor, even when the order of the filter is increased. But the acausal filter (green) shows a phase shift relative to the original data. This phase shift increases drastically when increasing the order of the filter.\n",
    "\n",
    "4) Zooming into a time window from 4.5 s to 5 s and setting the maximum amplitude to 400, we see that the phase shift is also shifting the first onset. We would pick it incorrectly. Therefore, whenever the scientific task involves the correct time picking of phases, we have to work with causal filters. When only the frequency content is important, we can also work with acausal filters.\n",
    "\n",
    "5) In the first two bands (0.01-0.05 Hz) we see Love waves with different amplitudes between 200 and 400 seconds. At 0.1-0.5 Hz we see Rayleigh waves after around 350 seconds and some scatter in the earlier times. At 0.5-1 Hz it is nearly all scattered energy. At 1-5 Hz we see a clear P-wave at around 25 seconds and some later scatter. The last band between 5 and 10 Hz removes the scatter completely with a very nice P-wave coda remaining. We can even distinguish the P-wave of a much smaller event at around 390 seconds.\n",
    "\n",
    "6) There is no clear S-wave visible. Also in the horizontal components (channel 0 and 1) almost no S-wave energy is visible. This is a clear hint for an explosive type of event. Indeed, this is the recording of a nuclear test explosion. The recording with exactly these bandpass filters was used as cover figure for the book 'Quantitative Seismology' by Keiiti Aki and Paul G. Richards, 2nd edition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "rise": {
   "scroll": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
