{
 "metadata": {
  "name": "powerspec"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [

    {
     "cell_type": "markdown",
     "metadata": {},
     "source": ["# Plotting the power spectrum of a time series"]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": ["import numpy as np\n", "from scipy import fft, arange\n", "\n", "def plot_spectrum(y,Fs):\n", "    \"\"\"\n", "    Plots a Single-Sided Amplitude Spectrum of y(t)\n", "    \"\"\"\n", "    n = len(y) # length of the signal\n", "    k = arange(n)\n", "    T = n/Fs\n", "    frq = k/T             # two sides frequency range\n", "    frq = frq[range(n/2)] # one side frequency range\n", "\n", "    Y = fft(y)/n          # fft computing and normalization\n", "    Y = Y[range(n/2)]\n", " \n", "    plot(frq,abs(Y),'r')  # plotting the spectrum\n", "    xlabel('Freq (Hz)')\n", "    ylabel('|Y(freq)|')\n", "\n", "# Generate time series\n", "Fs = 150.0;         # sampling rate\n", "Ts = 1.0/Fs;        # sampling interval\n", "t = arange(0,1,Ts)  # time vector\n", "\n", "ff = 5;   # frequency of the signal\n", "y = np.sin(2*np.pi*ff*t)\n", "\n", "# Add noise\n", "ynoise = y.copy()\n", "ynoise[0] = 1.0\n", "for j in range(len(t)-1):\n", "    ynoise[j+1] = 0.2*ynoise[j] + 0.5*np.random.normal()\n", "noise_amp = 0.5\n", "y += noise_amp * ynoise\n", "\n", "# Plot figure\n", "figure()\n", "subplot(2,1,1)\n", "plot(t,y)\n", "xlabel('Time')\n", "ylabel('Amplitude')\n", "subplot(2,1,2)\n", "plot_spectrum(y,Fs)\n", "show()\n", ""],
     "language": "python",
     "metadata": {},
     "outputs": [

      {
       "output_type": "pyout",
       "prompt_number": 2,
       "text": ["\n", ""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 3,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 4,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 5,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 6,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 7,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 8,
       "text": [""]
      },
      {
       "output_type": "pyout",
       "prompt_number": 9,
       "text": [""]
      },
      {
       "output_type": "display_data",
       "png": "[encoded data, 37192 characters]"
      }
     ],
     "prompt_number": 1
    }

   ],
   "metadata": {}
  }
 ]
}

