scipy

see SciPy Tutorial

SciPy is a collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data.

The additional benefit of basing SciPy on Python is that this also makes a powerful programming language available for

For brevity and convenience, we will often assume that the main packages (numpy, scipy, and matplotlib) have been imported as:

SciPy is organized into subpackages covering different scientific computing domains. These are summarized in the following table:

Scipy sub-packages need to be imported separately, for example:

Interaction with Numpy

Scipy builds on Numpy, and for all basic array handling needs you can use Numpy functions:

>>>>>> import numpy as np

>>> np.some_function()

To use functions from some of the Scipy modules, you can do:

>>>>>> from scipy import some_module

>>> some_module.some_function()

The top level of scipy also contains functions from numpy and numpy.lib.scimath. However, it is better to use them directly from the numpy module instead.

see SciPy Tutorial

**Intro**SciPy is a collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data.

The additional benefit of basing SciPy on Python is that this also makes a powerful programming language available for

**use in developing sophisticated programs and specialized application**Scientific applications using SciPy benefit from the development of additional modules in numerous niche’s of the software landscape by developers across the world. Everything from parallel programming to web and data-base subroutines and classes have been made available to the Python programmer. All of this power is available in addition to the mathematical libraries in SciPy. s.For brevity and convenience, we will often assume that the main packages (numpy, scipy, and matplotlib) have been imported as:

>>>>>> import numpy as np>>>>>> import numpy as np

**>>> import scipy as sp****>>> import matplotlib as mpl****>>> import matplotlib.pyplot as plt**SciPy is organized into subpackages covering different scientific computing domains. These are summarized in the following table:

**Subpackage Description****cluster Clustering algorithms****constants Physical and mathematical constants****fftpack Fast Fourier Transform routines****integrate Integration and ordinary differential equation solvers****interpolate Interpolation and smoothing splines****io Input and Output****linalg Linear algebra****ndimage N-dimensional image processing****odr Orthogonal distance regression****optimize Optimization and root-finding routines****signal Signal processing****sparse Sparse matrices and associated routines****spatial Spatial data structures and algorithms****special Special functions****stats Statistical distributions and functions****weave C/C++ integration**Scipy sub-packages need to be imported separately, for example:

**>>> from scipy import linalg, optimize**Interaction with Numpy

Scipy builds on Numpy, and for all basic array handling needs you can use Numpy functions:

>>>>>> import numpy as np

>>> np.some_function()

To use functions from some of the Scipy modules, you can do:

>>>>>> from scipy import some_module

>>> some_module.some_function()

The top level of scipy also contains functions from numpy and numpy.lib.scimath. However, it is better to use them directly from the numpy module instead.

Index Tricks

There are some class instances that make special use of the slicing functionality to provide efficient means for

For example, rather than writing something like the following

>>>>>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0)))

with the r_ command one can enter this as

>>>>>> r_[3,[0]*5,-1:1:10j]

which can ease typing and make for more readable code. Notice how objects are concatenated, and the

The

Another very useful class instance which makes use of extended slicing notation is the

Polynomials

There are two (interchangeable) ways to deal with 1-d polynomials in SciPy. The first is to use the

The other way to handle polynomials is as an array of coefficients with the first element of the array giving the coefficient of the highest power. There are explicit functions to add, subtract, multiply, divide, integrate, differentiate, and evaluate polynomials represented as sequences of coefficients.

There are some class instances that make special use of the slicing functionality to provide efficient means for

**array construction**. This part will discuss the operation of np.mgrid , np.ogrid , np.r_ , and np.c_ for quickly constructing arrays.For example, rather than writing something like the following

>>>>>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0)))

with the r_ command one can enter this as

>>>>>> r_[3,[0]*5,-1:1:10j]

which can ease typing and make for more readable code. Notice how objects are concatenated, and the

**slicing syntax**is (ab)used to construct ranges. The other term that deserves a little explanation is the use of the**complex number 10j as the step size in the slicing syntax**. This non-standard use allows the number to be interpreted as the number of points to produce in the range rather than as a step size (note we would have used the long integer notation, 10L, but this notation may go away in Python as the integers become unified).The

**“r” stands for row concatenation**because if the objects between commas are**2 dimensional arrays, they are stacked by rows**(and thus must have commensurate columns). There is an equivalent command c_ that stacks 2d arrays by columns but works identically to r_ for 1d arrays.Another very useful class instance which makes use of extended slicing notation is the

**function****mgrid**. In the simplest case, this function can be used to construct 1d ranges as a convenient substitute for arange. It also allows the use of complex-numbers in the step-size to indicate the number of points to place between the (inclusive) end-points. The real purpose of this function however is to produce N, N-d arrays which provide coordinate arrays for an N-dimensional volume.Polynomials

There are two (interchangeable) ways to deal with 1-d polynomials in SciPy. The first is to use the

**poly1d class from Numpy.**This class accepts coefficients or polynomial roots to initialize a polynomial. The polynomial object can then be manipulated in algebraic expressions, integrated, differentiated, and evaluated. It even prints like a polynomial:**>>>>>> p = poly1d([3,4,5])****>>> print p****2****3 x + 4 x + 5****>>> print p*p****4 3 2****9 x + 24 x + 46 x + 40 x + 25****>>> print p.integ(k=6)****3 2****x + 2 x + 5 x + 6****>>> print p.deriv()****6 x + 4****>>> p([4,5])****array([ 69, 100])**The other way to handle polynomials is as an array of coefficients with the first element of the array giving the coefficient of the highest power. There are explicit functions to add, subtract, multiply, divide, integrate, differentiate, and evaluate polynomials represented as sequences of coefficients.

Vectorizing functions (vectorize)

One of the features that NumPy provides is a class vectorize to convert an ordinary Python function which accepts scalars and returns scalars into a “vectorized-function” with the same broadcasting rules as other Numpy functions (

>>>>>> def addsubtract(a,b): ...

if a > b: ...

return a - b ...

else: ...

return a + b

which defines a function of two scalar variables and returns a scalar result. The class vectorize can be used to “vectorize “this function so that

>>>>>> vec_addsubtract = vectorize(addsubtract)

returns a function which takes array arguments and returns an array result:

>>>>>> vec_addsubtract([0,3,6,9],[1,3,5,7])

array([1, 6, 1, 2])

This particular function could have been written in vector form without the use of vectorize . But, what if the function you have written is the result of some optimization or integration routine. Such functions can likely only be vectorized using vectorize.

Other useful functions

There are also several other useful functions which should be mentioned. For doing

Some additional useful functions can also be found in the module scipy.misc. For example the

Finally, two functions are provided that are useful

One of the features that NumPy provides is a class vectorize to convert an ordinary Python function which accepts scalars and returns scalars into a “vectorized-function” with the same broadcasting rules as other Numpy functions (

*i.e.*the Universal functions, or ufuncs). For example, suppose you have a Python function named addsubtract defined as:>>>>>> def addsubtract(a,b): ...

if a > b: ...

return a - b ...

else: ...

return a + b

which defines a function of two scalar variables and returns a scalar result. The class vectorize can be used to “vectorize “this function so that

>>>>>> vec_addsubtract = vectorize(addsubtract)

returns a function which takes array arguments and returns an array result:

>>>>>> vec_addsubtract([0,3,6,9],[1,3,5,7])

array([1, 6, 1, 2])

This particular function could have been written in vector form without the use of vectorize . But, what if the function you have written is the result of some optimization or integration routine. Such functions can likely only be vectorized using vectorize.

Other useful functions

There are also several other useful functions which should be mentioned. For doing

**phase processing, the functions angle, andunwrap**are useful. Also, the**linspace and logspace functions return equally spaced samples in a linear or log scale**. Finally, it’s useful to be aware of the**indexing capabilities of Numpy**. Mention should be made of the function**select which extends the functionality of where to include multiple conditions and multiple choices**. The calling convention isselect(condlist,choicelist,default=0). select is a vectorized form of the multiple if-statement. It allows rapid construction of a function which returns an array of results based on a list of conditions. Each element of the return array is taken from the array in a choicelist corresponding to the first condition in condlist that is true. For example

>>>>>> x = r_[-2:3]>>>>>> x = r_[-2:3]

**>>> x****array([-2, -1, 0, 1, 2])****>>> np.select([x > 3, x >= 0],[0,x+2])****array([0, 0, 2, 3, 4])**

Some additional useful functions can also be found in the module scipy.misc. For example the

**factorial and comb functions compute and using either exact integer arithmetic (thanks to Python’s Long integer object), or by using floating-point precision and the gamma function**. Another function returns a common image used in**image processing: lena**.Finally, two functions are provided that are useful

**for approximating derivatives of functions using discrete-differences**. The**function central_diff_weights returns weighting coefficients for an equally-spaced -point approximation to the derivative of order**. These weights must be multiplied by the function corresponding to these points and the results added to obtain the derivative approximation. This function is intended for use when only samples of the function are available. When the function is an object that can be handed to a routine and evaluated, the*o***function derivative can be used to automatically evaluate the object at the correct points to obtain an N-point approximation to the**.*o*-th derivative at a given pointSpecial functions (scipy.special)

The main feature of the scipy.special package is the definition of numerous special functions of mathematical physics. Available functions include airy, elliptic, bessel, gamma, beta, hypergeometric, parabolic cylinder, mathieu, spheroidal wave, struve, and kelvin. There are also some low-level stats functions that are not intended for general use as an easier interface to these functions is provided by the stats module. Most of these functions can take array arguments and return array results following the same broadcasting rules as other math functions in Numerical Python. Many of these functions also accept complex numbers as input. For a complete list of the available functions with a one-line description type >>> help(special). Each function also has its own documentation accessible using help. If you don’t see a function you need, consider writing it and contributing it to the library. You can write the function in either C, Fortran, or Python. Look in the source code of the library for examples of each of these kinds of functions.

The main feature of the scipy.special package is the definition of numerous special functions of mathematical physics. Available functions include airy, elliptic, bessel, gamma, beta, hypergeometric, parabolic cylinder, mathieu, spheroidal wave, struve, and kelvin. There are also some low-level stats functions that are not intended for general use as an easier interface to these functions is provided by the stats module. Most of these functions can take array arguments and return array results following the same broadcasting rules as other math functions in Numerical Python. Many of these functions also accept complex numbers as input. For a complete list of the available functions with a one-line description type >>> help(special). Each function also has its own documentation accessible using help. If you don’t see a function you need, consider writing it and contributing it to the library. You can write the function in either C, Fortran, or Python. Look in the source code of the library for examples of each of these kinds of functions.