Python SciPy library is a set of convenience functions built on NumPy and mathematical algorithms.
- At present Python SciPy library supports integration, gradient optimization, special functions, ordinary differential equation solvers, parallel programming tools and many more; in other words, we can say that if something is there in general textbook of numerical computation, there are high chances you’ll find it’s implementation in SciPy.
- An interactive session with SciPy is basically a data-processing and system-prototyping environment just like MATLAB, Octave, Scilab or R-lab.
- SciPy is an open source project, released under BSD license.
SciPy provides high-level commands and classes for data-manipulation and data-visualization, which increases the power of an interactive Python session by significant order.
In addition to mathematical algorithms in SciPy, everything from classes and web and database subroutines to parallel programming is available to Python programmer, making it easier and faster to develop sophisticated and specialized applications.
Since SciPy is open source, developers across the world can contribute to the development of additional modules which is much beneficial for scientific applications using SciPy.
Install SciPy Library
We’ll discuss some basic functions and important features of SciPy but before let’s install SciPy. We can install SciPy packages simply by using
pip, run the following command in terminal (add
sudo if you have to):
pip install scipy
To install this package with conda run:
conda install -c anaconda scipy
Importing Scipy Library
To start using Scipy in our python projects, we will just import Scipy as:
Interacting with Numpy
As we already know SciPy is built on NumPy, so for all basic needs we can use NumPy functions itself:
numpy.lib.scimath are also contained in SciPy, but it’s recommended to use them directly and not go through SciPy in this case.
Working with Polynomials
In SciPy, there are two ways in which we can deal with 1D polynomials. First one is using the class
poly1d. This class takes coefficients or roots for initialization and forms a polynomial object. When we print this object we’ll see it prints like a polynomial. Let’s have a look at example code:
from numpy import poly1d # We'll use some functions from numpy remember!! # Creating a simple polynomial object using coefficients somePolynomial = poly1d([1,2,3]) # Printing the result # Notice how easy it is to read the polynomial this way print(somePolynomial) # Let's perform some manipulations print("nSquaring the polynomial: n") print(somePolynomial* somePolynomial) #How about integration, we just have to call a function # We just have to pass a constant say 3 print("nIntegrating the polynomial: n") print(somePolynomial.integ(k=3)) #We can also find derivatives in similar way print("nFinding derivative of the polynomial: n") print(somePolynomial.deriv()) # We can also solve the polynomial for some value, # let's try to solve it for 2 print("nSolving the polynomial for 2: n") print(somePolynomial(2))
The program when run gives output like below image, I hope comments made it clear what each piece of code is trying to do:
Another way to handle polynomials is to use an array of coefficients. There are functions available to perform operations on polynomials represented as sequences, first method looks much easier to use and give output in a readable manner, so I prefer first one for the instance.
SciPy Example – Linear Algebra
SciPy holds very fast linear algebra capabilities as it’s built using ATLAS LAPACK and BLAS libraries. The libraries are even available to use if you want more speed but you have to dig deep in that case.
All the linear algebra routines in SciPy take an object that can be converted into a 2D array and the output is of the same type.
Let’s have a look at linear algebra routine with help of an example. We’ll try to solve a linear algebra system which can easily be done using scipy command
This method expects input matrix and right-hand side vector:
# Import required modules/ libraries import numpy as np from scipy import linalg # We are trying to solve a linear algebra system which can be given as: # 1x + 2y =5 # 3x + 4y =6 # Create input array A= np.array([[1,2],[3,4]]) # Solution Array B= np.array([,]) # Solve the linear algebra X= linalg.solve(A,B) # Print results print(X) # Checking Results print("n Checking results, following vector should be all zeros") print(A.dot(X)-B)
Let’s run this script now:
The integrate sub-package of scipy provides various integration techniques. We can have a look at these simply by typing:
Let’s try to integrate a lambda in a script:
# Import required packages from scipy import integrate # Using quad as we can see in list quad is used for simple integration # arg1: A lambda function which returns x squared for every x # We'll be integrating this function # arg2: lower limit # arg3: upper limit result= integrate.quad(lambda x: x**2, 0,3) print(result)
Again, we have added enough comments so that the code is utmost clear. Let’s run this now:
The second item in result here is possible error in result, we can ignore it for now.
SciPy Fourier Transforms
Fourier analysis helps us to express a function as a sum of periodic components and for recovering the signal from those components.
Let’s look at a simple example of Fourier transformation. We’ll be plotting sum of two sines:
# Import Fast Fourier Transformation requirements from scipy.fftpack import fft import numpy as np # Number of sample points N = 600 # sample spacing T = 1.0 / 800.0 x = np.linspace(0.0, N*T, N) y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x) yf = fft(y) xf = np.linspace(0.0, 1.0/(2.0*T), N//2) # matplotlib for plotting purposes import matplotlib.pyplot as plt plt.plot(xf, 2.0/N * np.abs(yf[0:N//2])) plt.grid() plt.show()
The output should be similar to this:
Not to the surprise, Matplotlib drew the graph.
SciPy Special Functions
The special sub-package of SciPy has definitions of numerous functions of mathematical physics. The functions available include airy, Bessel, beta, elliptic, gamma, hypergeometric, Kelvin, Mathieu, parabolic cylinder, spheroidal wave and struve. Let’s have a look at Bessel function.
Bessel functions are a family of solutions to Bessel’s differential equation with real or complex order alpha.
Let’s have a better look at it with help of an example, the example is of a circular drum anchored at edge:
# Import special package from scipy import special import numpy as np def drumhead_height(n, k, distance, angle, t): kth_zero = special.jn_zeros(n, k)[-1] return np.cos(t) * np.cos(n*angle) * special.jn(n, distance*kth_zero) theta = np.r_[0:2*np.pi:50j] radius = np.r_[0:1:50j] x = np.array([r * np.cos(theta) for r in radius]) y = np.array([r * np.sin(theta) for r in radius]) z = np.array([drumhead_height(1, 1, r, theta, 0.5) for r in radius]) # Plot the results for visualization import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()
The code on running plots following graph:
Some functions like binary entropy function, Heaviside step function and ramp function are straightforward to implement with help of existing functions NumPy and SciPy and thus are not included in this package.
In this post, we discovered the SciPy Python library for easy and efficient mathematical operations.
We learned that it is a vast library used for scientific application development and where sophisticated and complex mathematical operations are to be taken care of, like in Machine Learning / Deep Learning. We also had a look at how scipy package helps us in performing various mathematical operations.
Reference: Official Website