Contents

This page hosts "recipes", or worked examples of commonly-done tasks. Some are introductory in nature, while others are quite advanced (these are at the bottom of the page). We encourage new users to post recipes even for simple tasks that are not yet represented here. Our goal is an easy learning experience for new users. Some of these recipes may be incorporated into tutorials in the future.

**Scipy** Central

You can find and submit more recipes at http://

**scipy**-central.org/ (which eventually can supersede this wiki page)

# NumPy / **SciPy**

NumPy arrays: tips and tricks:

Building Arrays Introduction to numerical arrays.

Indexing Indexing numpy arrays, from simple to complicated.

Multiplying multiple arguments Generalizing

`dot(a,b)`to the case of N arguments.Segment axis Devious trick using strides to allow general operations (like convolution) on successive, overlapping pieces of an array

Stride tricks for the Game of Life This is similar to Segment axis, but for 2D arrays with 2D windows.

MetaArray Class for storing per-axis meta data information with an array (axis names, column names, units, etc.)

Obarray Trick for avoiding object arrays when dealing with arrays of objects.

Recarray Accessing array columns with structured arrays and recarrays.

accumarray-like function A function that behaves like MATLAB's accumarray.

- Linear Algebra
Rank and nullspace of a matrix.

- Interpolation:
Interpolation Examples of interpolation (see also Gridding irregularly spaced data).

Radial Basis Functions Using radial basis functions for smoothing/interpolation

- Optimization and fitting techniques:
Optimization Quick example of fminbound with plot.

Optimization with fit Similar to above with spline fit and chaco plot.

Fitting Data Day to day work in the lab: fitting experimental data.

Linear regression Simple Linear regression example.

Fit statistics Estimates a multi-variate regression model and provides various fit statistics.

Least Squares Circle Fitting the least squares circle from a series of 2D points

RANSAC algorithm Implementation of the robust estimation method.

- Ordinary differential equations
Zombie Apocalypse ODE Modeling Modeling a Zombie Apocalypse by solving a system of ordinary differential equations using the

**SciPy**routine,*odeint*.A coupled spring-mass system Another example of solving differential equations.

Lotka-Volterra Tutorial Solving ordinary differential equations with

**Scipy**KdV Solving the Korteweg-deVries equation on a periodic domain using the pseudo-spectral method with the method of lines.

- Root finding
Spherical Bessel Zeros Finding the zeros of the spherical Bessel functions and its derivative

Intersection of functions Compute the points at which two given functions intersect.

Data rebinning Examples of rebinning data to produce smaller arrays with and without interpolation.

Histograms 2D histograms with variable bin width

Convex Hull Finds the convex hull around a set of data points.

Minimum Point of a Convex Hull Finds the minimum point of the convex hull of a finite set of points.

Kalman Filtering Example from the Welch & Bishop Introduction to the Kalman Filter.

Comm Theory Example of BPSK simulation.

Smoothing a signal Performing smoothing of 1D and 2D signals by convolving them with a window.

Butterworth Bandpass Filter Create and apply a Butterworth bandpass filter.

FIR Filter Design Design a low-pass FIR filter using the window method.

How to apply a FIR filter: signal.convolve, signal.fftconvolve, ndimage.convolve1d or signal.lfilter?

A zero phase delay filter Sample code for a null phase delay filter that processes the signal in the forward and backward direction removing the phase delay.

Savitzky Golay filtering of data Sample code for Savitzky Golay filtering.

Frequency-swept signals Generating frequency-swept signals with chirp() and sweep_poly() from

**scipy**.signal (**SciPy**0.8)Multithreading Easy multithreading for embarrassingly parallel problems

KDTree Searching multidimensional space using kd-trees.

Particle Filter A simple particle filter algorithm for tracking objects in a video sequence.

Brownian Motion Compute Brownian motion (i.e. the Wiener process).

Correlated Random Samples Generate correlated normally distributed random samples.

Large Markov Chains Find the stationary distribution of a large Markov chain; the M/M/1 tandem queue

Watershed algorithm Apply the watershed algorithm in order to split an array into distinct components (e.g. for the segmentation of an image into objects).

Linear Classification Fisher's discriminant function and Probabilistic Generative model

Plot an eye diagram using numpy and matplotlib.

## Advanced topics

Views vs Copies A quick introduction to array views and some caveats on situations where you should expect a data view or a data copy.

# Compiling Extensions

Compiling Extensions on Windows A quick tutorial on how to compile extension modules on Windows using MinGW

# Scientific Scripts

SchrÃ¶dinger's equation: a 1-d FDTD solver that animates the time evolution of a gaussian wave packet interacting with simple potentials.

# Input Output

DataFrames A useful class for storing alphanumerical data, similar to GNU R's data frames.

Data acquisition with PyUniversalLibrary A series of examples using an inexpensive USB data acquisition device from Measurement Computing.

Data acquisition with Ni-DAQmx A simple example of using ctypes and numpy to access data acquisition devices from National Instruments.

input/output Reading and writing a NumPy array from/to an ascii/binary file.

Fortran I/O Reading FORTRAN record-structured binary files (if you don't know what these are, thank your stars and you don't need this).

Reading SPE files Reading SPE binary files produced by CCD cameras (Princeton and like).

Reading LAS files Reading LAS (Log ASCII Standard) well log files.

# Graphics

There are several packages available to produce interactive screen graphics (use the mouse to zoom, orient, and fine-tune) and publication-quality printed plots, in 2D, 3D, and 4D (animations). These packages have releases more frequently than **SciPy**. Rather than bundling out-of-date packages with **SciPy**, the plotting packages are released separately. However, their developers work closely with the **SciPy** developers to ensure compatibility.

Matplotlib cookbook. Matplotlib is the preferred package for 2D graphics.

3D plotting with Mayavi. Advanced 3D data visualization with MayaVi2 (and TVTK): a very powerful interactive scientific data visualizer.

Python Imaging Library. Create/manipulate images as numpy array's.

Plotting with xplt. xplt is very fast but less flexible than matplotlib. It allows simple 3-d surface visualizations as well. It is based on pygist (included) and is available under the sandbox directory in SVN

**scipy**.Mat3d. Simple 3D plotting using an OpenGL backend.

Line Integral Convolution code in cython for visualizing vector fields

VTK volume rendering. This is a simple example that show how to use VTK to volume render your three dimensional numpy arrays.

Old Matplotlib recipes. The recipes on this page are being contributed to the Matplotlib project and will eventually be deleted from this Wiki.

# Using NumPy With Other Languages (Advanced)

A comparison of Weave with NumPy, Pyrex, Psyco, Fortran and C++ using Laplace's equation as an example.

Using Pyrex and NumPy to share data between your Pyrex/C extension module and NumPy.

Using Pyrex and the array_struct interface to access array data without requiring a C dependency on Numeric, numarray, or NumPy.

**NumInd**: A Numerical Agnostic Pyrex Class to access Numeric/numarray/NumPy arrays in an uniform way from both C and Pyrex space.Using SWIG and NumPy to access and modify NumPy arrays in C libraries.

**numpy.i**: A few SWIG and numpy.i basic examples.**numpy.i**: Using SWIG and numpy.i to handle automatic C memory deallocation from Python (using a modified numpy.i).Using f2py to wrap Fortran codes.

Using f2py and Numpy to wrap C codes.

Writing C Extensions.

Using ctypes with NumPy.

Using /Weave and

**iterators**for fast, generalized code.

# Scientific GUIs

Using wxPython dialogs for simple user interaction.

Using TraitsUI to build interactive applications.

**List of all pages in the category "Cookbook":**- Cookbook
- Cookbook/A Numerical Agnostic Pyrex Class
- Cookbook/ArrayStruct and Pyrex
- Cookbook/BuildingArrays
- Cookbook/C Extensions
- Cookbook/C Extensions/NumPy arrays
- Cookbook/CommTheory
- Cookbook/Ctypes
- Cookbook/Data Acquisition with PyUL
- Cookbook/F2Py
- Cookbook/Finding Convex Hull
- Cookbook/Histograms
- Cookbook/InputOutput
- Cookbook/KDTree
- Cookbook/KalmanFiltering
- Cookbook/LoktaVolterraTutorial
- Cookbook/Matplotlib
- Cookbook/MayaVi
- Cookbook/MayaVi/Examples
- Cookbook/MayaVi/RunningMayavi2
- Cookbook/MayaVi/ScriptingMayavi2
- Cookbook/MayaVi/ScriptingMayavi2/BasicModules
- Cookbook/MayaVi/ScriptingMayavi2/Filters
- Cookbook/MayaVi/ScriptingMayavi2/MainModules
- Cookbook/MayaVi/Tips
- Cookbook/MayaVi/tvtk
- Cookbook/MetaArray
- Cookbook/Multithreading
- Cookbook/OptimizationDemo1
- Cookbook/PIL
- Cookbook/Pyrex and NumPy
- Cookbook/RANSAC
- Cookbook/Rebinning
- Cookbook/SWIG Memory Deallocation
- Cookbook/SWIG NumPy examples
- Cookbook/SWIG and NumPy
- Cookbook/SavitzkyGolay
- Cookbook/SchrodingerFDTD
- Cookbook/ViewsVsCopies
- Cookbook/Weave
- Cookbook/dbase
- Cookbook/f2py and NumPy
- Cookbook/hdf5 in Matlab
- Cookbook/multiprocessing
- Cookbook/vtkVolumeRendering
- NumPy for Matlab Users