Book Image

Scientific Computing with Python 3

By : Claus Führer, Jan Erik Solem, Olivier Verdier
Book Image

Scientific Computing with Python 3

By: Claus Führer, Jan Erik Solem, Olivier Verdier

Overview of this book

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.
Table of Contents (23 chapters)
Scientific Computing with Python 3
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Acknowledgement
Preface
References

Preface

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.

What this book covers

Chapter 1, Getting Started, addresses the main language elements of Python without going into detail. Here we make a brief tour through all. It is a good starting point for those who want to start directly. It is a quick reference for those readers who want in a later chapter understand an example which uses might use constructs like functions before functions were explained in deep .

Chapter 2, Variables and Basic Types, presents the most important and basic types in Python. Float is the more important datatype in scientific computing together with the special numbers nan and inf. Booleans, integers, complex, and strings are other basic datatypes, which will be used throughout this book.

Chapter 3, Container Types, explains how to work with container types, mainly lists. Dictionaries and tuples will be explained as well as indexing and looping, through container objects. Occasionally, one uses even sets as a special container type.

Chapter 4, Linear Algebra, works with the most important objects in linear algebra--vectors and matrices. This book chooses NumPy array as the central tool for describing matrices and even higher order tensors. Arrays have many advanced features and allows also for universal functions acting on matrices or vectors elementwise. The book emphasizes on array indexing, slices, and the dot product as the basic operation in most computing tasks. Some linear algebra examples are worked out to demonstrate the use of SciPy's submodule linalg.

Chapter 5, Advanced Array Concepts, explains some more advanced aspects of arrays. The difference between array copies and views is explained extensively as views make programs using arrays very fast but are often a source for errors, which are hard to debug. The use of Boolean arrays to write effective, compact, and readable code is shown and demonstrated. Finally, the technique of array broadcasting-- a unique feature of NumPy arrays -- is explained by its analogy to operations performed on functions.

Chapter 6, Plotting, shows how to make plots, mainly classical x/yplots but also 3D plots and histograms. Scientific computing requires good tools for visualizing the results. Python's module matplotlib is introduced starting from the handy plotting commands in its submodule pyplot. Finetuning and modifying plots becomes possible by creating graphical objects such as axes. We show how attributes of these objects can be changed and annotations can be made.

Chapter 7, Functions, form the fundamental building block in programming, which is probably nearest to underlying mathematical concepts. Function definition and function calls are explained as the different ways to set function arguments. Anonymous lambda functions are introduced and used in various examples throughout the book.

Chapter 8, Classes, defines objects as instances of classes, which we provide with methods and attributes. In mathematics, class attributes often depend on each other, which requires special programming techniques for setter and getter functions. Basic mathematical operations such as + can be defined for special mathematic datatypes. Inheritance and abstraction are mathematical concepts which are reflected by object oriented programming. We demonstrate the use of inheritance by a simple solver class for ordinary differential equations.

Chapter 9, Iterating, presents iteration using loops and iterators. There is now a chapter in this book without loops and iterations, but here we come to principles of iterators and create own generator objects. In this chapter, you learn why a generator can be exhausted and how infinite loops can be programmed. Python's module itertools is a useful companion for this chapter.

Chapter 10, Error Handling, covers errors and exceptions and how to find and fix them. An error or an exception is an event, which breaks the execution of a program unit. This chapter shows what to do then, that is, how an exception can be handled. You learn to define your own exception classes and how to provide valuable information, which can be used for catching these exceptions. Error handling is more than printing an error message.

Chapter 11, Namespaces, Scopes and Modules, covers Python modules. What are local and global variables? When is a variable known and when is it unknown to a program unit? This is discussed in this chapter. A variable can be passed to a function by a parameter list or tacitly injected by making use of its scope. When should this technique be applied and when not? This chapter tries to give an answer to this central question.

Chapter 12, Input and Output, covers some options for handling data files. Data files are used for storing and providing data for a given problem, often large scale measurements. This chapter describes how this data can be accessed and modified using different formats.

Chapter 13, Testing, focuses on testing for scientific programming. The key tool is unittest, which allows for automatic testing and parametrized tests. By considering the classical bisection algorithm in numerical mathematics, we exemplify different steps to design meaningful tests, which as a side effect also deliver a documentation of the use of a piece of code. Careful testing provides test protocols which can be later helpful when debugging a complex code often written by many different programmers.

Chapter 14, Comprehensive Examples, presents some comprehensive and longer examples together with a brief introduction to the theoretical background and their complete implementation. These examples make use of all constructs shown in the book so far and put them in a larger and more complex context. They are open for extensions by the reader.

Chapter 15, Symbolic Computations - SymPy, speaks about symbolic computations. Scientific computing is mainly numeric computations with inexact data and approximative results. This is contrasted by symbolic computations often formal manipulation, which aims for exact solutions in a closed form expression. In this last chapter of the book, we introduce this technique in Python, which is often used for deriving and verifying theoretically mathematical models and numerical results. We emphasize on high precision floating point evaluation of symbolic expressions.

What you need for this book

You would need Pyhon3.5 or higher, SciPy, NumPy, Matplotlib, IPython shell (we recommend strongly to install Python and its packages through Anaconda). The examples of the book do not have any special hardware requirements on memory and graphics.

Who this book is for

This book is the outcome of a course on Python for scientific computing which is taught at Lund University since 2008. The course expanded over the years, and condensed versions of the material were taught at universities in Cologne, Trondheim, Stavanger, Soran, Lappeenranta and also in computation oriented companies.

Our belief is that Python and its surrounding scientific computing ecosystem — SciPy, NumPY and matplotlib — represent a tremendous progress in scientific computing environment. Python and the aforementioned libraries are free and open source. What’s more, is a modern language featuring all the bells and whistles that this adjective entails: object oriented programming, testing, advanced shell with IPython, etc. When writing this book we had two groups of readers in mind:

  • The reader who chooses Python as his or her first programming language will use this book in a teacher-led course. The book guides into the different topics and offers background reading and experimenting. A teacher typically selects and orders the material from this book in such a way, that it fits to the specific learning outcomes of an introductory course.
  • The reader who already has some experience in programming, and some taste for scientific computing or mathematics will use this book as a companion when diving into the world of Scipy and Numpy. Programming in Python can be quite different from programming in MATLAB, say. The book wants to point out the "pythonic" way of programming, which makes programming a pleasure.

Our goal is to explain the steps to get started with Python in the context of scientific computing. The book may be read either from the first page to the last, or by picking the bits that seem most interesting. Needless to say, as improving one’s programming skills requires considerable practice, it is highly advisable to experiment and play with the examples and the exercises in the book.

We hope that the readers will enjoy programming with Python, SciPy, NumPY and matplotlib as much as we do.

Python vs Other Languages

When it comes to deciding what language to use for a book on scientific computing many factors come in to play. The learning threshold of the language itself is important for newcomers, here scripting languages usually provide the best options. A wide range of modules for numerical computing is necessary, preferably with a strong developer community. If these core modules are built on a well-tested, optimized foundation of fast libraries like e.g. LAPACK, even better. Finally, if the language is also usable in a wider setting and a wider range of applications, the chance of the reader using the skills learned from this book outside an academic setting is greater. Therefore the choice of Python was a natural one.

In short, Python is

  • free and open source
  • a scripting language, meaning that it is interpreted
  • a modern language (object oriented, exception handling, dynamic typing etc.)
  • concise, easy to read and quick to learn
  • full of freely available libraries, in particular scientific ones (linear algebra, visualization tools, plotting, image analysis, differential equations solving, symbolic computations, statistics etc.)
  • useful in a wider setting: scientific computing, scripting, web sites, text parsing, etc.
  • widely used in industrial applications

There are other alternatives to Python. Some of them and the differences to Python are listed here.

Java, C++ : Object oriented, compiled languages. More verbose and low level compared to Python. Few scientific libraries.

C, FORTRAN : Low level compiled languages. Both languages are extensively used in scientific computing, where computational time matters. Nowadays these languages are often combined with Python wrappers.

PHP, Ruby, other interpreted languages. PHP is web oriented. Ruby is as flexible as Python but has few scientific libraries.

MATLAB, Scilab, Octave : MATLAB is a tool for matrix computation that evolved for scientific computing. The scientific library is huge. The language features are not as developed as those of Python. Neither free nor open source. SciLab and Octave are open source tools which are syntactically similar to MATLAB.

Haskell : Haskell is a modern functional language and follows different programming paradigms than Python. There are some common constructions like list comprehension. Haskell is rarely used in scientific computing. See also [12].

Other Python literature

Here we give some hints to literature on Python which can serve as complementary sources or as texts for parallel reading. Most introductory books on Python are devoted to teach this language as a general purpose tool. One excellent example which we want to mention here explicitly is [19]. It explains the language by simple examples, e.g. object oriented programming is explained by organizing a pizza bakery.

There are very few books dedicated to Python directed towards scientific computing and engineering. Among these few books we would like to mention the two books by Langtangen which combine scientific computing with the modern "pythonic" view on programming, [16,17].

This "pythonic" view is also the guiding line of our way of teaching programming of numerical algorithms. We try to show how many well-established concepts and constructions in computer science can be applied to problems within scientific computing. The pizza-bakery example is replaced by Lagrange polynomials, generators become time stepping methods for ODEs, and so on.

Finally we have to mention the nearly infinite amount of literature on the web. The web was also a big source of knowledge when preparing this book. Literature from the web often covers things that are new, but can also be totally outdated. The web also presents solutions and interpretations which might contradict each other. We strongly recommend to use the web as additional source, but we consider a "traditional" textbook with the web resources "edited" as the better entry point to a rich new world.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, and user input are shown as follows: "install additional packages with conda install within your virtual environment"

A block of code is set as follows:

from scipy import *
from matplotlib.pyplot import *

Any command-line input or output is written as follows:

jupyter notebook

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The Jupyter notebook is a fantastic tool for demonstrating your work."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Scientific-Computing-with-Python-3. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ScientificComputingwithPython3_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.