Docsity

python for signal processing, Notas de estudo de Engenharia Elétrica

Pré-visualização parcial do texto

Baixe python for signal processing e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

José Unpingco

Python

for Signal

Processing

Featuring IPython Notebooks

Python for Signal Processing

José Unpingco

Python for Signal Processing

Featuring IPython Notebooks

123

José Unpingco San Diego, CA USA

ISBN 978-3-319-01341-1 ISBN 978-3-319-01342-8 (eBook) DOI 10.1007/978-3-319-01342- Springer Cham Heidelberg New York Dordrecht London

Library of Congress Control Number: 2013946655

© Springer International Publishing Switzerland 2014 This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Springer is part of Springer Science+Business Media (www.springer.com)

Preface

This book will teach you the fundamentals of signal processing via the Python language and its powerful extensions for scientific computing. This is not a good first book in signal processing because we assume that you already had a course in signal processing at the undergraduate level. Furthermore, we also assume that you have some basic understanding of the Python language itself, perhaps through an online course (e.g., codeacademy.com). Having said that, this book is appropriate if you have a basic background in signal processing and want to learn how to use the scientific Python toolchain. On the other hand, if you are comfortable with Python, perhaps through working in another scientific field, then this book will teach you the fundamentals of signal processing. Likewise, if you are a signal processing engineer using a commercial package (e.g., MATLAB, IDL), then you will learn how to effectively use the scientific Python toolchain by reviewing concepts you are already familiar with. The unique feature of this book is that everything in it is reproducible using Python. Specifically, all of the code, all of the figures, and (most of) the text is available in the downloadable supplementary materials that correspond to this book in the form of IPython Notebooks. IPython Notebooks are live interactive documents that allow you to change parameters, recompute plots, and generally tinker with all of the ideas and code in this book. I urge you to download these IPython Notebooks and follow along with the text to experiment with the signal processing topics covered. As an open-source project, the entire scientific Python toolchain, including the IPython Notebook, is freely available. Having taught this material for many years, I am convinced that the only way to learn is to experiment as you go. The text provides instructions on how to get started installing and configuring your scientific Python environment. This book is not designed to be exhaustive and reflects the author’s eclectic background in industry. The focus is on fundamentals for day-to-day work. Al- though Python supports many powerful constructs such as decorators, generators, and context managers, all the code here uses Python in the most straightforward way possible while encouraging good Python coding practices.

vii

Contents

  • 1 Introduction
    • 1.1 Introduction
    • 1.2 Installation and Setup..
    • 1.3 Numpy
      • 1.3.1 Numpy Arrays and Memory
      • 1.3.2 Numpy Matrices
      • 1.3.3 Numpy Broadcasting
    • 1.4 Matplotlib
    • 1.5 Alternatives to Matplotlib
    • 1.6 IPython
      • 1.6.1 IPython Notebook
    • 1.7 Scipy
    • 1.8 Computer Algebra
    • 1.9 Interfacing with Compiled Libraries
    • 1.10 Other Resources
    • Appendix
  • 2 Sampling Theorem
    • 2.1 Sampling Theorem
    • 2.2 Reconstruction
    • 2.3 The Story So Far
    • 2.4 Approximately Time-Limited-Functions
    • 2.5 Summary
    • Appendix
  • 3 Discrete-Time Fourier Transform
    • 3.1 Fourier Transform Matrix
    • 3.2 Computing the DFT
    • 3.3 Understanding Zero-Padding..
    • 3.4 Summary
    • Appendix
  • 4 Introducing Spectral Analysis x Contents
    • 4.1 Seeking Better Frequency Resolution with Longer DFT
    • 4.2 The Uncertainty Principle Strikes Back!
    • 4.3 Circular Convolution
    • 4.4 Spectral Analysis Using Windows
    • 4.5 Window Metrics
      • 4.5.1 Processing Gain
      • 4.5.2 Equivalent Noise Bandwidth..
      • 4.5.3 Peak Sidelobe Level
      • 4.5.4 3-dB Bandwidth
      • 4.5.5 Scalloping Loss
    • 4.6 Summary
    • Appendix
  • 5 Finite Impulse Response Filters
    • 5.1 FIR Filters as Moving Averages
    • 5.2 Continuous-Frequency Filter Transfer Function
    • 5.3 Z-Transform..
    • 5.4 Causality
    • 5.5 Symmetry and Anti-symmetry
    • 5.6 Extracting the Real Part of the Filter Transfer Function
    • 5.7 The Story So Far
    • 5.8 Filter Design Using the Window Method
      • 5.8.1 Using Windows for FIR Filter Design..
    • 5.9 The Story So Far
    • 5.10 Filter Design Using the Parks-McClellan Method
    • 5.11 Summary
    • Appendix
  • References
  • Symbols
  • Index
  • Erratum E

2 1 Introduction

that were not otherwise designed to work together. Moreover, Python provides a multiplatform solution for scientific codes. As an open-source project, Python itself is available anywhere you can build it, even though it typically ships standard nowadays, as part of many operating systems. This means that once you have written your code in Python, you can just transfer the script to another platform and run it, as long as the compiled libraries are also available there. What if the compiled libraries are absent? Building and configuring compiled libraries across multiple systems used to be a painstaking job, but as scientific Python has matured, a wide range of libraries have now become available across all of the major platforms (i.e. Windows, MacOS, Linux, Unix) as prepackaged distributions. Finally, scientific Python facilitates maintainability of scientific codes because Python syntax is clean, free of semi-colon litter and other visual clutter that makes code hard to read and easy to obfuscate. Python has many built-in testing, documentation, and deployment tools that ease maintenance. Scientific codes are usually written by scientists unschooled in software development, so having these development tools built into the language itself is a particular boon for scientific computing.

1.2 Installation and Setup

The easiest way to get started is to download the freely available Anaconda package from Continuum Analytics, which is available for all the major platforms. If you need it, Continuum also offers support for an additional fee. On Windows work- stations, the free PythonXY distribution is a one-click installation of the scientific Python toolchain, as well as many other packages. On the major Linux distributions, the toolchain is usually available via the package manager (i.e. apt-get, yum). Regardless of your platform, we recommend the Python version 2.7 distributions. Python 2.7 is the “last” of the Python 2.x series and guarantees backwards compatibility with legacy codes. Python 3.x makes no such guarantees. Although all of the key components of the Python toolchain are available in version 3.x, the safest bet is to stick with version 2.7 until further notice. Enthought Canopy is the next generation of the Enthought Python Distribution (EPD), which is an enterprise- level scientific Python integrated development environment. The “Express” version of Canopy is available for free and works on all the major platforms. You may later want to use a Python module that is not part of the major scientific Python distributions mentioned above and that you have to build yourself. The Windows platform presents singular difficulties because of the lack of freely available compilers (especially for Fortran) and the general difficulty of working with this complicated platform. A great place to look for high quality one-click installers is Christoph Gohlke’s laboratory site at the University of California, Irvine where he kindly makes a long list of scientific modules available. Otherwise, Python packages on other platforms can be installed using easy_install or pip.

1.3 Numpy 3

1.3 Numpy

To use a compiled scientific library, the memory allocated in the Python interpreter must somehow reach this library as input. Furthermore, the output from these libraries must likewise return to the Python interpreter. This two-way exchange of memory is essentially the core function of the Numpy (numerical arrays in Python) module. Numpy is the de-facto standard for numerical arrays in Python. It arose as an effort by Travis Oliphant and others to unify the many approaches to numerical arrays in Python. In this section, we provide an overview and some tips for using Numpy effectively, but for much more detail, Travis’ book Guide to Numpy [Oli06] is still a great place to start and is available for free in PDF form. Numpy provides specification of byte-sized arrays in Python. For example Listing 1.1 creates an array of three numbers, each of 4-bytes long (32 bits at 8 bits per byte) as shown by the itemsize property in Listing 1.1. In addition to providing uniform containers for numbers, Numpy provides a long list if unary functions ( ufuncs ) that process arrays element-wise without additional looping semantics. Listing 1.2 shows how to compute the element-wise sine using Numpy, Listing 1.2 shows computing the sine using Numpy where the input is a Numpy array and the output is the element-wise sine of that array. Numpy uses common- sense casting rules to resolve the output types. For example, if the inputs had been an integer-type, the output would still have been a floating point type. Further, observe that there was no Python looping construct (e.g. for loop) required to compute this element-wise because this happens in the compiled code that is invoked by the unary function. In this example, we provided a Numpy array as input to the sine function. We could have also used a plain Python list instead and Numpy would have built the intermediate Numpy array (e.g. np.sin([1,1,1])). The Numpy Documentation provides a comprehensive (and very long) list of available ufuncs. Numpy arrays come in various shapes and dimensions. For example, Listing 1. shows a two-dimensional 2x3 array constructed from two conforming Python lists. Note that you can have as many as 32 dimensions and if you need more then you can build Numpy to your specification. 1 Numpy arrays follow the usual Python slicing rules, but in more dimensions as shown in Listing 1.4 where the “:” character selects all elements along a particular axis. You can also select sub-sections of arrays by using slicing as shown in Listing 1..

1.3.1 Numpy Arrays and Memory

Some interpreted languages implicitly allocate memory. For example, in MATLAB, you can extend a matrix by simply tacking on another dimension as in the MATLAB

(^1) See arrayobject.h

1.4 Matplotlib 5

1.3.3 Numpy Broadcasting

Numpy broadcasting is a powerful way to make implicit multidimensional grids for expressions. It is probably the single most powerful feature of Numpy and the most difficult to grasp. Proceeding by example, consider the vertices of a two-dimensional unit square in Listing 1.. Listing 1.14 shows the X and Y arrays whose corresponding entries match the coordinates of the vertices of the unit square (e.g. .0; 0/; .0; 1/; .1; 0/; .1; 1/). To add the x and y-coordinates, we could use X and Y as in X+Y shown below in Listing 1.15 , The output is the sum of the vertex coordinates of the unit square. It turns out we can skip a step here and not bother with meshgrid to implicitly obtain the vertex coordinates by using broadcasting as shown in Listing 1.. Listing 1.16 shows how to avoid the intermediate meshgrid calculation by using Numpy broadcasting to create the intermediate arrays. This happens on line 7 where the None Python singleton tells Numpy to make copies of y along this dimension to create a conformable calculation. The following lines show that we obtain the same output as when we used the X+Y Numpy arrays. Note that without broadcasting x+y=array([0, 2]) which is not what we are trying to compute. Let’s continue with a more complicated example where we have differing array shapes. Listing 1.17 shows that broadcasting works with different array shapes. For the sake of comparison, on line 3, meshgrid creates two conformable arrays, X and Y. On the last line, x+y[:,None] produces the same output as X+Y without the meshgrid. We can also put the None dimension on the x array as x[:,None]+y which would give the transpose of the result. Broadcasting works in multiple dimensions also. Listing 1.18 shows broad- casting in three dimensions. The output shown has shape (4,3,2). On the last line, the x+y[:,None] produces a two-dimensional array which is then broadcast against z[:,None,None], which duplicates itself along the two added dimensions to accommodate the two-dimensional result on its left (i.e. x + y[:,None]). The caveat about broadcasting is that it can potentially create large intermediate arrays. There are methods for controlling this by re-using previously allocated memory but that is beyond our scope here. Some codes use a lot of broadcasting and some not at all. We use it occasionally in this text where it abbreviates superfluous looping.

1.4 Matplotlib

Matplotlib is the primary visualization tool for scientific graphics in Python. Like all great open-source projects, it originated to satisfy a personal need. At the time of its inception, John Hunter primarily used MATLAB for scientific visualization, but as he began to integrate data from disparate sources (e.g. internet, filesystems) using Python, he realized he needed a Python solution for visualization, so he single- handedly wrote Matplotlib. Since those early years, Matplotlib has displaced the

6 1 Introduction

other competing methods for two-dimensional scientific visualization and today is a very actively maintained project, even without John Hunter, who sadly passed away in 2012. John had a few basic requirements for Matplotlib:

  • Plots should look publication quality with beautiful text.
  • Plots should output Postscript for inclusion within LATEX documents and publi- cation quality printing.
  • Plots should be embeddable in a Graphical User Interface (GUI) for application development.
  • The code should be mostly Python to allow for users to become developers.
  • Plots should be easy to make with just a few lines of code for simple graphs.

Each of these requirements has been completely satisfied, judging from the enthusiastic reception of Matplotlib by the scientific Python community. In the beginning, to ease the transition from MATLAB to Python, many of the Matplotlib functions were closely named after the corresponding MATLAB commands. The community has moved away from this style and, even though you will still find the old MATLAB-esque style used in the Matplotlib documentation. This book uses the more powerful and explicit Matplotlib interfaces. Listing 1.19 shows the quickest way to draw a plot using Matplotlib and the plain Python interpreter. Later, we’ll see how to do this even faster using IPython. The first line imports the requisite module as plt which is the recommended convention. The next line plots a sequence of numbers generated using Python’s range function. Note the output list contains a Line2D object. This is an artist in Matplotlib parlance. Finally, the plt.show() function draws the plot in a GUI (i.e. figure window ). If you try this in your own plain Python interpreter (and you should!), you will see that you cannot type in anything further in the interpreter until the figure window is closed. This is because the plt.show() function preoccupies the interpreter with the controls in the GUI and blocks further interaction. As we discuss below, IPython provides ways to get around this blocking so you can simultaneously interact with the interpreter and the figure window. The plot function returns a list containing the Line2D object as shown in Listing 1.19. More complicated plots yield larger lists filled with artists in Matplotlib terminology. The suggestion is that artists draw on the canvas contained in the Matplotlib figure. The final line is the plt.show function that provokes the embedded artists to render on the Matplotlib canvas. The reason this is a separate function is that plots may have dozens of complicated artists and rendering may be a time-consuming task to only be undertaken at the end, when all the artists have been mustered. Matplotlib supports plotting types such as images, contours, and many others that we cover in detail in the following chapters. Even though Listing 1.19 is the quickest way to draw a plot in Matplotlib, it is not recommended because there are no handles to the intermediate products of the plot such as the plot’s axis. While this is okay for a simple plot like this, later on we will see how to construct complicated plots using the recommended style. There

8 1 Introduction

to already know (or be willing to learn) about concepts like graphics pipelines. This package is actively supported and well-documented.

1.6 IPython

IPython originated as a way to enhance Python’s basic interpreter for smooth interactive scientific development. In the early days, the most important enhance- ment was “tab-completion” for dynamic introspection of workspace variables. For example, you can start IPython at the commandline by typing ipython and then you should see something like the following in your terminal:

IPython 0.14.dev -- An enhanced Interactive Python. ? -> Introduction and overview of IPython’s features. %quickref -> Quick reference. help -> Python’s own help system. object? -> Details about ’object’, use ’object??’ for extra details.

In [1]:

Next, creating a string as shown and hitting the TAB key after the “dot” character initiates the introspection, showing all the functions and attributes of the string object in x.

In [1]: x = ’this is a string’

In [2]: x. x.capitalize x.format x.isupper x.rindex x.strip x.center x.index x.join x.rjust x.swapcase x.count x.isalnum x.ljust x.rpartition x.title x.decode x.isalpha x.lower x.rsplit x.translate x.encode x.isdigit x.lstrip x.rstrip x.upper x.endswith x.islower x.partition x.split x.zfill x.expandtabs x.isspace x.replace x.splitlines x.find x.istitle x.rfind x.startswith

To get help about any of these, you simply add the? character at the end as shown below,

In [2]: x.center? Type: builtin_function_or_method String Form:<built-in method center of str object at 0x03193390> Docstring: S.center(width[, fillchar]) -> string

Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)

1.6 IPython 9

and IPython provides the built-in help documentation. Note that you can also get this documentation with help(x.center) which works in the plain Python interpreter as well. The combination of dynamic tab-based introspection and quick interactive help accelerates development because you can keep your eyes and fingers in one place as you work. This was the original IPython experience, but IPython has since grown into a complete framework for delivering a rich scientific computing workflow that retains and enhances these fundamental features.

1.6.1 IPython Notebook

As you may have noticed investigating Python on the web, most Python users are web-developers, not scientific programmers, meaning that the Python toolchain is very well developed for web technologies. The genius move of the IPython development team was to leverage these technologies for scientific computing by embedding IPython in modern web-browsers. You can start the IPython Notebook, with all the Matplotlib and Numpy functions set up with the following command- line: ipython notebook --pylab=inline. The inline flag embeds Matplotlib graphics created in the IPython Notebook into the browser itself instead of popping open a separate GUI. After starting the notebook, you should see something like the following in the terminal,

[NotebookApp] Using existing profile dir: u’C:\.ipython\profile_default’ [NotebookApp] Serving notebooks from local directory: D:
[NotebookApp] The IPython Notebook is running at: http://127.0.0.1:8888/ [NotebookApp] Use Control-C to stop this server and shut down all kernels.

The first line reveals where IPython looks for default settings. The next line shows where it looks for documents in the IPython Notebook format. The third line shows that the IPython Notebook started a web-server on the local machine (i.e. 127.0.0.1) on port number 8888. This is the address your browser needs to connect to the IPython session although your default browser should have opened automatically to this address. The port number and other configuration options are available either on the commandline or in the profile_default shown in the first line. If you are on a Windows platform and you do not get this far, then the Window’s firewall is probably blocking the port. For additional configuration help, see the main IPython site (ipython.org) or e-mail the very responsive IPython mailing list ([email protected]). When IPython starts, it initiates many small Python processes that use the blazing-fast ZeroMQ message passing framework for interprocess-communication, along with the web-sockets protocol for back-and-forth communication with the browser. As of yet, because neither Internet Explorer nor Safari support web- sockets, you will have to use Firefox or Google Chrome to use the IPython Notebook. To start IPython and get around your default browser, you can use the additional –-no-browser flag and then manually type in the local host address