Docsity

beginning python visualization, Notas de estudo de Engenharia Elétrica

Toggle sidebar
bg1
Vaingast
Shelve in
Programming Languages/General
User level:
Beginning–Intermediate
www.apress.com
SOURCE CODE ONLINE
BOOKS FOR PROFESSIONALS BY PROFESSIONALS®
Beginning Python Visualization:
Crafting Visual Transformation Scripts
We are visual animals. But before we can see the world in its true splendor, our brains,
just like our computers, have to sort and organize raw data, and then transform that
data to produce new images of the world. Beginning Python Visualization: Crafting Visual
Transformation Scripts, Second Edition discusses turning many types of data sources,
big and small, into useful visual data. And, you will learn Python as part of the bargain.
In this second edition you’ll learn about Spyder, which is a Python IDE with MATLAB®-like
features. Here and throughout the book, you’ll get detailed exposure to the growing
IPython project for interactive visualization. In addition, you’ll learn about the changes
in NumPy and SciPy that have occurred since the first edition. Along the way, you’ll get
many pointers and a few visual examples.
As part of this update, you’ll learn about matplotlib in detail; this includes creating
3D graphs and using the basemap package that allows you to render geographical
maps. Finally, you’ll learn about image processing, annotating, and filtering, as well as
how to make movies using Python. This includes learning how to edit/open video files
and how to create your own movie, all with Python scripts
Beginning Python Visualization teaches you:
• How to present visual information instead of data soup
• How to set up an open source environment ready for data visualization
• How to do numerical and textual processing
• How to draw graphs and plots based on textual and numerical data
using NumPy, Spyder, and more
• How to explore and use new visual libraries including matplotlib’s
3D graphs and basemap package
• How to build and use interactive visualization using IPython
SECOND
EDITION
RELATED
9781484 200537
54999
ISBN 978-1-4842-0053-7
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe beginning python visualization e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

For your convenience Apress has placed some of the front

matter material after the index. Please use the Bookmarks

and Contents at a Glance links to access them.

xxv

Introduction

I have always been drawn to math and computers, ever since I was a kid playing computer games on my Sinclair ZX81. When I attended university, I had a special interest in numerical analysis, a field that I feel combines math and computers ideally. During my career, I learned of MATLAB, widely popular for digital signal processing, numerical analysis, and feedback and control. MATLAB’s strong suits include a high-level programming language, excellent graphing capabilities, and numerous packages from almost every imaginable engineering field. But I found that MATLAB wasn’t enough. I worked with very large files and needed the ability to manipulate both text and data. So I combined Perl, AWK, and Bash scripts to write programs that automate data analysis and visualization. And along the way, I’ve developed practices and ideas involving the organization of data, such as ways to ensure file names are unique and self-explanatory. With the increasing popularity of the Internet, I learned about GNU/Linux and the open source movement. I’ve made an effort to use open source software whenever possible, and so I’ve learned of GNU-Octave and gnuplot, which together provide excellent scientific computing functionality. That fit well on my Linux machine: Bash scripts, Perl and AWK, GNU-Octave, and gnuplot. Knowing I was interested in programming languages and open source software, a friend suggested I give Python a try. My first impression was that it was just another programming language: I could do almost anything I needed with Perl and Bash, resorting to C/C++ if things got hairy. And I’d still need GNU-Octave and gnuplot, so what was the advantage? Eventually, I did learn Python and discovered that it is far better than my previous collection of tools. Python provides something that is extremely appealing: it’s a one-stop shop—you can do it all in Python. I’ve shared my enthusiasm with friends and colleagues. Many who expressed interest with the ideas of data processing and visualization would ask, “Can you recommend a book that teaches the ideas you’re preaching?” And I would tell them, “Of course, numerous books cover this subject! But they didn’t want numerous books, just one, with information distilled to focus on data analysis and visualization. I realized there wasn’t such a title, and this was how the idea for this book originated.

What’s New in the Second Edition

Aside from using the most up-to-date version of Python that supports all the visualization packages (version 3.3 at the time of the writing the second edition), I’ve also introduced the following additional content:

  • 3-D plots and graphs
  • Non-rectangular contour plots
  • Matplotlib’s basemap toolkit
  • Reading and writing MATLAB binary files
  • Reading and writing data to NumPy arrays
  • Reading and writing images to NumPy arrays
  • Making movies
  • IPython, IPython Notebook, and Spyder development environments

■ IntroduCtIon

xxvi

Who This Book Is For

Although this book is about software, the target audience is not necessarily programmers or computer scientists. I’ve assumed the reader’s main line of work is research or R&D, in his or her field of interest, be it astrophysics, signal and image processing, or biology. The audience includes the following:

  • Graduate and PhD students in exact and natural sciences (physics, biology, and chemistry) working on their thesis, dealing with large experimental data sets. The book also appeals to students working on purely theoretical projects, as they require simulations and means to analyze the results.
  • R&D engineers in the fields of electrical engineering (EE), mechanical engineering, and chemical engineering: engineers working with large sets of data from multiple sources. In EE more specifically, signal processing engineers, communication engineers, and systems engineers will find the book appealing.
  • Programmers and computer enthusiasts, unfamiliar with Python and the GNU/Linux world, but who are willing to dive into a new world of tools.
  • Hobbyist astronomers and other hobbyists who deal with data and are interested in using Python to support their hobby.

The book can be appealing to these groups for different reasons. For scientists and engineers, the book provides the means to be more productive in their work, without investing a considerable amount of time learning new tools and programs that constantly change. For programmers and computer enthusiasts, the book can serve as an appetizer, opening up their world to Python. And because of the unique approach presented here, they might share the enthusiasm the author has for this wonderful software world. Perhaps it will even entice them to be part of the large and growing open source community, sharing their own code. It is assumed that the reader does have minimal proficiency with a computer, namely that he or she must know how to manipulate files, install applications, view and edit files, and use applications to generate reports and presentations. A background in numerical analysis, signal processing, and image processing, as well as programming, is also helpful, but not required. This book is not intended to serve as an encyclopedia of programming in Python and the covered packages. Rather, it is meant to serve as an introduction to data analysis and visualization in Python, and it covers most of the topics associated with that field.

How This Book Is Structured

The book is designed so that you can easily skip back and forth as you engage various topics. Chapter 1 is a case study that introduces the topics discussed throughout the book: data analysis, data management, and, of course, data visualization. The case study involves reading GPS data, analyzing it, and plotting it along with relevant annotations (direction of travel, speed, etc.). A fully functional Python script will be built from the ground up, complemented with lots of explanations. The fruit of our work will be an eye-catching GPS route. If you’re new to data analysis and visualization, consider reading Chapter 2 first. The chapter describes how to set up a development environment to perform the tasks associated with data analysis and visualization in Python, including the selection of an OS, installing Python, and installing third-party packages. If you’re new to Python, your next stop should be Chapter 3. In this chapter, I swiftly discuss the Python programming language. I won’t be overly rehashing basic programming paradigms; instead I’ll provide a quick overview of the building blocks for the Python programming. Regardless of your Python programming experience, I highly encourage you to read Chapter 4 before proceeding to the next chapters. Organization is the key to successful data analysis and visualization. This chapter covers organizing data files, pros and cons of different file formats, file naming conventions, finding data files, and automating file creation. The ideas in Chapter 4 are used throughout the book.

Chapter 1

Navigating the World of Data

Visualization

A Case Study

As an engineer, I work with data all the time. I parse log files, analyze data, estimate values, and compare the results with theory. Things don’t always add up. So I double-check my analysis, perform more calculations, or run simulations to understand the results better. I refer to previous work because the ideas are similar or sometimes because they’re dissimilar. I look at the graphs and realize I’m missing some crucial information. So I add the missing data, but it’s noisy and needs filtering. Eventually, I realize my implementation of the algorithm is poor or that there is a better algorithm with better results, and so it’s back to square one. It’s an iterative process: tweak, test, and tweak again until I’m satisfied with the results. Those are the tasks surrounding research and development (R&D) work. And to be honest, there’s no systematic method. Most of the time, research is organized chaos. The emphasis, however, should be on “organized”, not “chaos”. Data should be analyzed and presented in a clear and coherent manner. Sources for graphs should be well understood and verified to be accurate. Algorithms should be tested and proven to be working as intended. The system should be flexible. Introducing new ideas and challenging previous methods should be easy, and testing new ideas on current data should be fast and efficient. In this book I will attempt to address all the topics associated with data processing and visualization: managing files and directories, reading files of varying formats, and performing signal processing and numerical analysis in a high-level programming language similar to MATLAB and GNU-Octave. Along the way, I will teach you Python, a rich and powerful programming language. In a nutshell, Beginning Python Visualization deals with the processing, analysis, manipulation, and visualization of data using the Python programming language. The book covers the following:

  • Fundamentals of the Python programming language required for data analysis and visualization.
  • Data files, format, and organization, as well as methods and guidelines for selecting file formats and storing and organizing data to enable fast, efficient data processing.
  • Readily available Python packages for numerical analysis, signal and image processing, graphing and plotting, and more.

To demonstrate what’s possible, this chapter will present a case study of using Python to gather GPS data, analyze the data prior to visualization, and plot the results.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Before we begin, however, you should understand a few fundamentals about Python. Python is an interpreted programming language. This means that each command is first read and then executed. This is in contrast to compiled programming languages, where the entire program is evaluated (compiled) and then executed. One of the important features of interpreted programming languages is that it’s easy to run them interactively. That is, you can perform a command, examine the results, perform more commands, examine more results, and so on. The ability to run Python interactively is very useful, and it allows you to examine topics as you learn them. It’s also possible to run programs, referred to as scripts , non-interactively in Python, and there are several ways to do that. You can run scripts from the interactive Python prompt by issuing the command exec(open('scriptname.py').read()). Or you can enter python scriptname.py at the command-line interface of your operating system. If you’re using IPython, you can issue the command run scriptname.py instead; and if you’re running IDLE, the Python GUI, you can open the script and press F5 to execute it. The .py extension is a common convention that distinguishes Python scripts from other files. The case study described in this chapter takes advantage of scripts, as well as running Python interactively.

■ Note it is important to be able to distinguish between interactive sessions and python scripts. When code starts

with >>>, it means that the code was run on python interactively. in cases where the ellipsis symbol (.. .) appears, it

means that the code is a continuation of a previously interactively entered command. lines of text following the symbols

... or >>> are python’s response to the issued command. a code listing that does not start with >>>is a script written

in an editor; in order to execute it, you will have to save it under scriptname.py (or some other name) and execute it as

described previously.

Gathering Data

We spend considerable time recording and analyzing data. Data is stored in various formats depending on the tools used to collect it, the nature of the data (e.g., pictures vs. sampled analog data), the application that will later process the data, and personal preferences. Data files are of varying sizes; some are very large, others are smaller but in larger quantities. Data organization adds another level of complexity. Files can be stored in directories according to date, grouped together in one big directory or in a database, or adhere to a different scheme altogether. Typically, the number of data files or the amount of data per file is too large to allow skimming or browsing with an editor or viewer. Methods and tools are required to find the data and analyze it to produce meaningful results. As you’ll soon see, Python provides all the tools required to do just that.

Case Study: GPS Data

You just got a USB GPS receiver for your birthday! You’d like to analyze GPS data and find out how often you exceed the speed limit and how much time you spend in traffic. You’d like to track data over a year, or even longer. You decide to record, analyze, and visualize the GPS data in Python. Some hardware background: most USB GPS receivers behave as serial ports (this is also true for Bluetooth GPS devices). This means that once a GPS is connected (assuming it’s installed properly), reading GPS data is as simple as opening the COM port associated with the GPS and reading the values. GPS values are typically clear text values: numbers and text. Of course, if you’re planning on recording GPS data from your car, it would make a lot of sense to hook it up to a laptop rather than a desktop.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

This is a rather quick introduction to Python! First, let’s dissect the code line-by-line. The first line, from serial.tools.list_ports import comports, allows us to access a function named comports(). By using the import command, we load the function comports() and are able to use it. The function comports() is part of a module (a module is a collection of functions and data structures) named tools. The package serial is a collection of modules associated with the serial port, one of which is tools. Accessing modules within packages is performed using the dot operator. This is something you’ll see a lot of in Python: from package.module import function (see Chapter 3 for more on this topic). The second line calls the function comports(); in both the Linux and the Windows versions, it returns a list of available serial ports. In the Linux version, the list is returned by calling the function comports() directly. In the Windows version, a rather more complex mechanism is used, called a generator expression. This is a rather advanced topic and is discussed in Chapter 3, so we will skip it for now. In both versions, the list is composed of pairs of values. The first value is the location of the serial port, and the second is a description. Write down the serial port location; you’ll need it for the next section.

Recording GPS Data

Let’s start gathering data. Enter the code in Listing 1-2 and save it in the file, record_gps.py.

Listing 1-2. record_gps.py

import time, serial

change these parameters to your GPS parameters

port = '/dev/ttyUSB0' # in Windows, set this to 'COMx' ser = serial.Serial(port)

ser.baudrate = 4800 fmt = "../data/GPS-%4d-%02d-%02d-%02d-%02d-%02d.csv"

filename = fmt % time.localtime()[0:6] f = open(filename, 'wb') while True: line = ser.readline() f.write(line) print(line)

■ Note if your gps does not support access through the serial port and you would like to follow along with this

chapter, you can download an example data file from the official website for this book and continue with that.

This time, we’ve imported another module: time. The time module provides access to date and time functions, and we’ll use those to name our GPS data files. We also introduce an important notion here: comments! Comments in Python are denoted by the # sign and are similar to C++ double slash notation, //. Everything in the line from that point onward is considered a remark. If the # sign is at the beginning of a line, then the entire line is a remark, usually describing the next line or block of code. The exception to the # sign indicating a remark occurs when it is quoted inside a string, as follows: "#".

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Don’t forget to change the value of the variable port to point at your serial port location as returned from the port scanning code in Listing 1-1. You should also set the proper baud rate. Determining the baud rate is not complex, but it’s best to consult the manual. Mine turned out to be 4800; if you’re not sure of yours, you can tweak this parameter. The script record_gps.py will print the output from the GPS onscreen so you can change the baud rate value (try the values 1200, 2400, 4800 and 9600) until you see some meaningful results (i.e., text and numbers). Running record_gps.py (I’ll get to how it works soon) yields GPS data:

>>> exec(open('record_gps.py').read())

$GPRMC,140053.00,A,4454.1740,N,09325.0143,W,000.0,128.7,300508,001.1,E,A*2E

$GPGGA,140053.00,4454.1740,N,09325.0143,W,1,09,01.1,00289.8,M,-030.7,M,,*5E

$GPGSA,A,3,21,15,18,24,26,29,06,22,,03,,,02.0,01.1,01.7*

$GPGSV,3,1,12,21,75,306,40,15,59,075,46,18,57,269,49,24,56,115,46*

$GPGSV,3,2,12,26,48,059,43,29,27,188,48,06,25,308,41,22,18,257,33*7D

$GPGSV,3,3,12,08,14,060,,03,11,320,32,09,06,144,,16,04,311,*7C

$GPRMC,140054.00,A,4454.1740,N,09325.0143,W,000.0,128.7,300508,001.1,E,A*

$GPGGA,140054.00,4454.1740,N,09325.0143,W,1,09,01.1,00289.8,M,-030.7,M,,*

$GPGSA,A,3,21,15,18,24,26,29,06,22,,03,,,02.0,01.1,01.7*

Data is being recorded to file as it is displayed. When you wish to stop viewing and recording GPS data, press Ctrl+C. If you’re running in an interactive Python, be sure to close the serial port once you issue Ctrl+C , or you won’t be able to rerun the script record_gps.py. To close the port, issue the following command:

>>> ser.close()

It’s also a good idea to close the file:

>>> f.close()

Let’s take a closer look at record_gps.py, to gain insight into how it works. The heart of the script lies in the following lines of code:

while True: line = ser.readline() f.write(line) print(line)

This is a straightforward implementation. The first line, while True:, instructs that the following block should be run indefinitely; that is, in an infinite loop. That’s why you need to press Ctrl+C to stop recording. The next three lines are then executed continuously. They read a line of text from the serial port, store it to file, and print it to screen. Reading GPS data is carried out by the command line = ser.readline(). Writing that data to a file for later processing is done by f.write(line). Printing the data to screen so the user has some visual feedback is done with print(line).

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Following these conventions, a file name might look like this:

GPS-2008-05-30-09-10-52.csv

Data Location

This is where we store data files:

  • All data files are stored in the directory,data. All scripts are stored in directory, src. Both directories are under the same parent directory, Ch1. So, a relative path from src to data is ../data. We’ll follow this convention throughout the book.
  • It’s also a good idea to add aReadme.txt file. Readme files are clear text files describing the contents of a directory, in as much detail as deemed reasonable. Such files typically describe the data source, data acquisition system, person in charge of data gathering, reason for gathering the data, and so on. Here’s an example:

Data recorded from a USB GPS receiver, connected to a Lenovo laptop T60. Data was gathered via the serial port stored to clear text files (CSV). Measurements were taken to estimate speed and time spent in traffic. Gathered by Shai Vaingast. Date: throughout 2008, see file timestamps.

Data Analysis

Once the data is organized and accessible in files, the next step is to extract information. Information can be a value, a graph, or a report pertaining to the problem at hand. The idea is to use Python’s scripting abilities and the wide range of readily available packages to write a fully automated application to process, analyze, and visualize data. Scripts are small pieces of code that are written relatively quickly in a high-level programming language. The key word here is productivity, the ability to change and test algorithms and extract results fast. Scripts might not be highly efficient in terms of processing speed, but written properly, they should not slow down running times. For example, a script might generate graphs or search the hard drive for data files, analyze log files, and extract the maximum and minimum temperatures. In our case, of course, we’ll use them to analyze GPS data. In our GPS case study, we’ll use the following algorithm:

  1. Compile a list of all the data files.
  2. For each file:

a. Read the data.

b. Process the data.

c. Plot the data.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Walking Directories

To compile a list of all the files with GPS data, we use the function os.walk() provided with the module os , which is part of the Python Standard Library. To use os , we issue import os:

>>> import os >>> for root, dirs, files in os.walk('../data'): ... print(root, dirs, files) ...

../data [] ['GPS-2008-05-30-09-00-50.csv', 'GPS-2008-05-30-09-10-52.csv', 'Readme.txt']

■ Note to be able to change directories within the python interpreter, first issue import os. then, to change to a

directory, issue os.chdir(directory_path). to list directory contents, you can use os.listdir(directory_path).

some interpreters, like ipython, let you use, among other enhancements, shell-like commands such as cd and ls, which

add considerable usability.

The function os.walk() iterates through the directory data and its subdirectories recursively, looking for files and folders, and then storing the results in variables root, dirs, and files. The second line prints out the root directory for the search. In our case, that means ../data (notice the relative path), then the subdirectories, and lastly, the files themselves, in a list. I’ve only recorded two data files thus far; but over time, more data is added to this folder, and the number of files can increase substantially. Since we have no subdirectories in folder data, the output corresponding to dirs should be an empty list, which is denoted by []. Using the function os.walk() is a bit of overkill here. In our case, directory data doesn’t have any subdirectories, and we could have just as easily listed the contents of the directory using the os.listdir() function call, as follows:

>>> os.listdir('../data')

['GPS-2008-30-05-09-00-50.csv', 'GPS-2008-30-05-09-10-52.csv', 'Readme.txt']

However, os.walk() is very useful. It’s not uncommon to have files grouped together in directories. And within those directories, you might have subdirectories holding still more files. For example, you might want to group files in accordance with the GPS that recorded the data. Or if another driver is recording GPS data, you might want to put that data in a separate subdirectory within your data directory. In those cases, os.walk() is exactly what’s needed. Now that we have a list of all the files in directory data, we can process only those with the .csv extension. We can do this using the endswith() function, which checks whether a string ends with “csv”. Files that do not end with “csv” are skipped using the continue command: continue instructs the for loop to skip the current execution and proceed to the next element. Files that do end with “csv” are read and processed. To create a full file name path from the directory and the file name, we use the function os.path.join(), as shown in Listing 1-3.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

len(x) tells us the size of the array of lists. It’s also a crude way for us to ensure that data was actually read into the array. The second line in the function is called a docstring , and it is characterized by three quotes (""") surrounding the text in the following manner: """dosctring""". In this case, a docstring is used to document the function; that is, it enables us to explain what it does. Issuing the command help(funcname) yields its docstring:

>>> help(read_csv_file)

Help on function read_csv_file in module main:

read_csv_file(filename) Reads a CSV file and return it as a list of rows.

You should use help() whenever you need a reminder of what a function does. help() can be invoked with functions as well as modules. For example, the following invokes help on module csv :

>>> help(csv)

Help on module csv:

NAME csv - CSV parsing and writing.

DESCRIPTION This module provides classes that assist in the reading and writing of Comma Separated Value (CSV) files, and implements the interface described by PEP 305. Although many CSV files are simple to parse, the format is not formally defined by a stable specification and is subtle enough that parsing lines of a CSV file with something like line.split(",") is bound to fail. The module supports three basic APIs: reading, writing, and registration of dialects.

The line data = [] declares a variable named data and initializes it as an empty list. We will use data to store the values from the CSV file. The csv module helps us read CSV files by automating a lot of the tasks associated with reading them. I will discuss CSV files and the csv module in more detail in Chapters 4 and 5; this chapter will only provide an overview. Here are the steps for reading CSV files with the csv module:

  1. Open the file for reading.
  2. Create a csv.reader object. The csv.reader object has functions that help us read CSV files.

a. Using the csv.reader object, read the data from the file, a row at a time.

b. Append every row to the variable data.

  1. Close the file.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Let’s try this, a step at a time:

>>> import csv >>> f = open('../data/GPS-2008-06-04-09-03-45.csv') >>> cr = csv.reader(f) >>> for row in cr: ... print(row)

['$GPGSA', 'A', '3', '21', '18', '15', '24', '', '22', '', '', '', '', '', '',

'03.5', '02.2', '02.7*09']

['$GPGSV', '3', '1', '12', '21', '86', '267', '39', '18', '66', '286', '44',

'15', '51', '060', '43', '24', '45', '125', '30*7A']

['$GPGSV', '3', '2', '12', '06', '28', '300', '33', '22', '27', '265', '31',

'03', '18', '312', '27', '29', '15', '185', '31*7C']

['$GPGSV', '3', '3', '12', '09', '15', '138', '31', '16', '00', '301', '',

'19', '00', '332', '', '00', '00', '000', '*70']

['$GPRMC', '140706.24', 'A', '4455.6241', 'N', '09328.0519', 'W', '011.4',

'152.7', '040608', '001.2', 'E', 'A*25']

['$GPGGA', '140706.24', '4455.6241', 'N', '09328.0519', 'W', '1', '04', '03.0',

'00295.1', 'M', '-030.7', 'M', '', '*51']

['$GPGSA', 'A', '3', '21', '18', '15', '24', '', '', '', '', '', '', '', '',

'08.9', '03.0', '08.4*04']

>>> f.close()

First, we open the data file and assign it to variable f. The opened file can now be referred to by the variable f. Next, we create a csv.reader object, cr. We associate the csv.reader object, cr, with the file f. We then iterate through every row of the csv.reader object and print that row. Lastly, we close the file by calling f.close(). It is considered good practice to close the file once you’re done with it; but if you neglect to do so, Python will close the file automatically once the variable f is no longer in use.

■ Note You may, after issuing the commands, receive an error similar to this: UnicodeEncodeError: 'charmap'

codec can't encode character '\uABCD'. if this happens, open the gps file in a text editor and make sure the file

contains proper alpha-numeric characters. Be sure to delete lines with non-alpha-numeric characters.

Python also lets you implement cascade functions , where you can call new functions based on the results of other functions. This process can be repeated several times. Cascading (usually) adds clarity and produces more elegant scripts. In our case, the variable f isn’t really important to us, so we discard it after we attach it to a csv.reader object. Instead of the preceding code, we can write the following, by cascading the functions:

>>> cr = csv.reader(open('../data/GPS-2008-06-04-09-03-45.csv')): >>> for row in cr: ... print(row)

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Listing 1-5. Function list_gps_commands( )

def list_gps_commands(data): """Counts the number of times a GPS command is observed.

Returns a dictionary object."""

gps_cmds = dict() for row in data: try: gps_cmds[row[0]] += 1 except KeyError: gps_cmds[row[0]] = 1

return gps_cmds

There are few things to keep in mind about this function. First, the docstring spans multiple lines, which is one of the key benefits of docstrings. Docstrings will display all the spaces and line breaks as shown in the function itself. Second, we initialize a variable, gps_cmds, to be our dictionary. We then process every list in the GPS data: we only care about the first element of every row, as that’s the value that holds the GPS header stamps. We then increment the value associated with the key: gps_cmds[row[0]] += 1. We use the += operation to increment the value by 1, similar to how it’s done in C (Python, however, does not use the ++ operator). If the key does not exist, which will happen whenever we encounter a new header stamp, an exception will be raised. We catch the exception with our except KeyError statement. In the case of an exception, we set the dictionary value associated with the key to 1. We can write the function list_gps_commands() even more compactly using the dictionary method get(); see Chapter 3 for details. Let’s analyze some GPS data:

>>> x = read_csv_file('../data/GPS-2008-05-30-09-00-50.csv') >>> list_gps_commands(x)

{'$GPGSA': 282, '$GPGSV': 846, '$GPGGA': 282, '$GPRMC': 283}

It turns out there are four distinct GPS headers being generated by my GPS. Of those, only two interest us: $GPGSV, which holds the number of satellites in view (Hey! It’s really important!); and $GPRMC, which holds location and velocity information. What we’d like to do is code a function that takes the GPS data and, whenever the header field is $GPGSV or $GPRMC, extracts the information and stores it in numerical arrays that will be easier to manipulate later on. Numerical arrays are introduced with the NumPy module, so we have to import numpy. Since we’ll be using a lot of the functionality of NumPy , SciPy , and matplotlib , an easier approach would be to import pylab, which imports all these modules, as follows:

>>> from pylab import *

■ Note the name PyLab comes from python and MatlaB. the PyLab module provides MatlaB-like functionality

in python.

Chapter 1 ■ NavigatiNg the World of data visualizatioN

Extracting GPS Data

In the case of a $GPGSV header, the number of satellites is the fourth entry. In the case of a $GPRMC header, we have a bit more interesting information. The second field is the timestamp, the fourth field is the latitude, the sixth field is the longitude, and the eighth field is the velocity. Again, refer to the NMEA 0183 format for more details. Table 1- summarizes the fields and their values in a $GPRMC line.

Table 1-1. $GPRMC Information (Excerpt)

Field Name Index Format

Header 0 $GPRMC (fixed)

Timestamp 1 hhmmss.ss

Latitude 3 DDMM.MMM

Longitude 5 DDDMM.MMM

Velocity 7 VVV.V

We need to keep in mind some caveats regarding the information in $GPRMC. For example, let’s look at the timestamp of an arbitrary line:

>>> x[12]

['$GPRMC', '140055.00', 'A', '4454.1740', 'N', '09325.0143', 'W', '000.0',

'128.7', '300508', '001.1', 'E', 'A*28']

In this output, the timestamp appears as '140055.00'. This follows the format hhmmss.ss where hh are two digits representing the hour (it will always consist of two digits—if the hour is one digit, say 7 in the morning, a 0 will be added before it), mm are two digits representing the minute (again, always two digits), and ss.ss are five characters (four digits plus the dot) representing seconds and fractions of seconds. There’s also a North/South field, as well as an East/West field. Here, for simplicity, we assume northern hemisphere, but you can easily change these values by reading the entire $GPRMC structure.

■ Note in the iso time format, we’ve used HHMMSS to denote hours minutes and seconds. in this case, we follow

the convention in NMea, which uses hhmmss.ss for hours, minutes, and seconds, and then sets DD and MM to angular

degrees and minutes.

The timestamp string is a bit hard to work with, especially when plotting data. The first reason is that it’s a string, not a number. But even if you translate it to a number, the system does not lend itself nicely to plotting because there are 60 seconds in a minute, not 100. So what we want to do is “linearize” the timestamp. To achieve this, we translate the timestamp as seconds elapsed since midnight, as follows: T = hh * 3600 + mm * 60 + ss.ss.