Skip to main content

Posts

Make Your Own GUI with Python

Suppose you have written a Python script that carries out a simulation based on a physical model and creates a nice plot of the results. Now you wish to explore the model and run the calculation on many different sets of input parameters. What is the best way to proceed? You could write a script that runs the same calculation on a list of inputs that you select ahead of time: inputs = [(x0, y0, z0), (x1, y1, z1), (x2, y2, z2)] for I in inputs: # Insert simulation code here. You could place your script inside a function and call the function repeatedly from the IPython command line with different inputs: def run_simulation(x, y, z): # Insert simulation code here. Both methods work, but neither is ideal. If you use a script with an input list, you have to select the inputs ahead of time. If you find an interesting region of parameter space, you have to modify the script and run it again. If you embed your simulation within a function, you have to do a lot of typing at ...

Jupyter Notebooks

Happy New Year! Let’s start off 2016 by learning something new: Jupyter Notebooks , formerly known as IPython Notebooks. A Jupyter notebook is an interactive document that incorporates text, math, graphics, and code. It can be viewed in a Web browser. Unlike most documents, however, you can modify and execute the code inside the document. In this sense, a Jupyter notebook is similar to a session in Mathematica or Maple. The difference is that the interpreter running behind the scenes is not Mathematica or Maple. Jupyter notebooks were designed to run Ju lia, Pyt hon, and R , but they support over 40 languages at present. The best way to learn about Jupyter notebooks is to take a look at one. This notebook is a simple example from a greenhorn, but you can find many more on the Web. Introduction.ipynb Click on the link to view the notebook. You can download the notebook using the Save icon at the upper right corner of the notebook Web page. You can then op...

Paths in Python

How do you get your Python interpreter to find modules that are not located in your current working directory? The answer is … you tell it where to look. When you type something like from my_module import my_function Python searches a collection of directories (i.e., folders) on your computer. If the directory containing <my_module.py> is not in this collection, you will receive an ImportError . This can be frustrating if you know the file exists, and even more so if you know where it exists. In this post, we will take a brief look at how to add paths to the collection of directories searched by Python. Paths A path is essentially a set of directions to a file: /Users/username/modules/my_module.py [Mac OS X, Linux] C:\modules\my_module.py [Windows] It tells your operating system how to navigate from a fixed starting point — the “root directory” / in Unix-based systems, or C:\ in Windows — through a co...

Speeding Up Python — Part 2: Optimization

The goal of this post and its predecessor is to provide some tools and tips for improving the performance of Python programs. In the previous post , we examined profiling tools — sophisticated stopwatches for timing programs as they execute. In this post, we will use these tools to demonstrate some general principles that make Python programs run faster. Remember: If your program already runs fast enough, you do not need to worry about profiling and optimization. Faster is not always better, especially if you end up with code that is difficult to read, modify, or maintain. Overview We can summarize our principles for optimizing performance as follows: Debug first. Never attempt to optimize a program that does not work. Focus on bottlenecks. Find out what takes the most time, and work on that. Look for algorithmic improvements. A different theoretical approach might speed up your program by orders of magnitude. Use library functions. The routines in NumPy, S...

Speeding Up Python — Part 1: Profiling

When people argue about programming languages, a common critique of Python is, “It’s slow.” This is occasionally followed by, “A program written in C will run a thousand times faster.” Such generalization carry little weight. Python is often fast enough, and a well-written Python program can run significantly faster than a poorly-written C program. Plus, Moore’s Law implies that computers today are over a thousand times faster than those of 15 years ago: You can do with Python today what was only possible with a highly optimized, compiled program in 2000. It is also important to consider development time. Suppose a C program takes a week to write and debug and 1 minute to run, and an equivalent Python program takes a day to write and debug and 1000 minutes (about a day) to run. The “slow” Python program will finish running five days earlier than the “fast” C program! If you already know Python and don’t know any C, t...

Lists, Comprehensions, and Generators

In A Student’s Guide to Python for Physical Modeling , we emphasized NumPy arrays and paid less attention to Python lists. The reason is simple: In most scientific computing applications, NumPy arrays store data more efficiently and speed up mathematical calculations, sometimes a thousandfold. However, there are some applications where a Python list is the better choice. There are also times when the choice between a list and an array has little or no effect on performance. In such cases a list can make your code easier to read and understand, and that is always a good thing. In this post, I will describe Python lists and explain a special Python construct for creating lists called a list comprehension . I will also describe a similar construct called a generator expression . Lists A list is an ordered collection of items. You may have made a “To Do” list this morning or a grocery list for a recent trip to the store. In computer science, a list is a data s...

Function Arguments: *args and **kwargs

In Python, functions can have positional arguments and named arguments . In this post, I will describe both types and explain how to use special syntax to simplify repetitive function calls with nearly the same arguments. This extends the discussion in section 5.1.3 of A Student’s Guide to Python for Physical Modeling . First, let’s look at np.savetxt , which has a straightforward declaration: $ import matplotlib.pyplot as plt $ from mpl_toolkits.mplot3d import Axes3D $ np.savetxt? Signature: np.savetxt( fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ') Docstring: Save an array to a text file. We see the function has two required arguments, followed by several optional arguments with default values. Next, let’s look at something more exotic: $ Axes3D.plot_surface? Signature: Axes3D.plot_surface(X, Y, Z, *args, **kwargs) Docstring: Create a surface plot. The f...