




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































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.
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:
■ IntroduCtIon
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:
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
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:
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.
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
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)
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())
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:
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:
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']
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:
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.
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)
>>> 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.
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)
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 *
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)
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]
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.
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.