Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python SciPy Tutorial

Python SciPy (1)

Python SciPy is a library that has Python NumPy and Mathematical algorithms as its building blocks. The Python SciPy library is utilized to a great extent in the field of scientific computations and processing.


Getting Started with Python Scipy

In order to use the different functions offered by the SciPy library, we need to install it. To serve the purpose, we will use pip command to install the SciPy library.

pip install scipy

In order to use the functions of this library, we will need to import this library using the following statement:

import scipy

Sub-Packages in Python SciPy

There are various sub-modules available in the SciPy library to perform and enhance the efficiency of the scientific calculations.

Some of the popular sub-modules of the SciPy library are listed below:

  • special: This sub-module contains the Special functions to perform a specific task.
  • constants: Represents constants.
  • optimize: This sub-module contains algorithms for optimization.
  • integrate: This sub-module contains functions to perform Mathematical Integration.
  • interpolate: Represents functions to perform interpolation.
  • linalg: Represents functions to perform operations on linear algebra equations.
  • io: It contains functions to perform Input/Output operations on the given input.
  • fftpack: Represents functions to perform Discrete Fourier Transform.
  • signal: Represents functions and tools for Signal Processing in Python.
  • sparse: Represents algorithms to deal with sparse matrices.
  • cluster: Represents functions to perform hierarchical clustering.

Linear Algebra with Python SciPy

Linear Algebra represents linear equations and represents them with the help of matrices.

The linalg sub-module of the SciPy library is used to perform all the functionalities related to linear equations. It takes the object to be converted into a 2-D NumPy array and then performs the task.


1. Solving a set of equations

Let us understand the working of the linalg sub-module along with the Linear equations with the help of an example:

4x+3y=12
3x+4y=18

Consider the above linear equations. Let us solve the equations through the linalg.solve() function.

from scipy import linalg
import numpy
X=numpy.array([[4,3],[3,4]])
Y=numpy.array([[12],[18]])
print(linalg.solve(X,Y))
X.dot(linalg.solve(X,Y))-Y

In the above snippet of code, we have passed the coefficients and constant values present in the input equations through numpy.array() function.

Further, linalg. solve() function solves the linear equations and displays the x and y value which works for that particular equation. equation1.dot(linalg.solve())-equation2 command is used to check the output of the equations.

Output:

[[-0.85714286]
 [ 5.14285714]]
array([[0.],
       [0.]])

array([[0.], [0.]]) ensures that the linear equations have been solved rightly.

[[-0.85714286] [ 5.14285714]]: These are the x and y values used to solve the linear equations.


2. Finding the Determinants of Matrices

The linalg.det() method is used to find the determinant of the input matrix.

Example:

from scipy import linalg
import numpy
determinant=numpy.array([[2,4],[4,12]])
linalg.det(determinant)

Output:

8.0

3. Calculating Inverse of a Matrix

The linalg.inv() method is used to calculate the inverse of an input matrix.

Example:

from scipy import linalg
import numpy
inverse=numpy.array([[2,4],[4,12]])
linalg.inv(inverse)

Output:

array([[ 1.5 , -0.5 ],
       [-0.5 ,  0.25]])

Performing calculations on Polynomials with Python SciPy

The poly1d sub-module of the SciPy library is used to perform manipulations on 1-d polynomials. It accepts coefficients as input and forms the polynomial objects.

Let’s understand the poly1d sub-module with the help of an example.

Example:

from numpy import poly1d

# Creation of a polynomial object using coefficients as inputs through poly1d
poly_input = poly1d([2, 4, 6, 8])

print(poly_input)

# Performing integration for value = 4
print("\nIntegration of the input polynomial: \n")
print(poly_input.integ(k=3))

# Performing derivation
print("\nDerivation of the input polynomial: \n")
print(poly_input.deriv())

In the above snippet of code, poly1d() is used to accept the coefficients of the polynomial.

Further, polynomial.integ(value) is used to find the integration of the input polynomial around the input scalar value. The polynomial.deriv() function is used to calculate the derivation of the input polynomial.

Output:

   3     2
2 x + 4 x + 6 x + 8

Integration of the input polynomial: 

     4         3     2
0.5 x + 1.333 x + 3 x + 8 x + 3

Derivation of the input polynomial: 

   2
6 x + 8 x + 6

Performing Integration with Python SciPy

The integrate sub-module of the SciPy library is used to perform integration on the input equations.

Let’s perform integration on the following equation:

3*x*2 + 2*x + 6

from scipy import integrate
integrate.quad(lambda x:3*x*2 + 2*x + 6,0,2) 

In the above piece of code, integrate.quad() function is used to calculate the integration of the input equation. It accepts the following arguments:

  • equation
  • upper limit
  • lower limit

Output:

(28.0, 3.1086244689504383e-13)

Fourier Transforms with Python SciPy

Fourier Transforms enable us to understand and depict functions as a summation of periodic components.

The fftpack sub-module of the SciPy library is used to perform Fourier transforms on the equations.

Example:

from scipy.fftpack import fft
import numpy as np

# Count of sample points
n = 400

# sample spacing
T = 1.0 / 500.0
x_i = np.linspace(0.0, n*T, n)
y_i = np.tan(70.0 * 2.0*np.pi*x_i) + 0.5*np.tan(70.0 * 2.0*np.pi*x_i)
y_f = fft(y_i)
x_f = np.linspace(0.0, 1.0/(3.0*T), n//2)

# matplotlib for plotting purposes
import matplotlib.pyplot as plt
plt.plot(x_f, 2.0/n * np.abs(y_f[0:n//2]))
plt.show()

In the above snippet of code, we have used numpy.linspace() function to get evenly spaced integers. Further, fft() function is used to calculate the Fourier value of the input. We have used the Python matplotlib module to plot the Tangent graph.

Output:

Fourier Transforms
Fourier TransformsTangent graph

Special Functions of Python SciPy

The following is the list of some of the most commonly used Special functions from the special package of SciPy:

  • Cubic Root
  • Exponential Function
  • Log-Sum Exponential Function
  • Gamma

1. Cubic Root

The scipy.special.cbrt() function is used to provide the element-wise cube root of the inputs provided.

Example:

from scipy.special import cbrt
val = cbrt([27, 8])
print(val)

Output:

[3. 2.]

2. Exponential Function

The scipy.special.exp10() function is used to calculate the element-wise exponent of the given inputs.

Example:

from scipy.special import exp10
val = exp10([27, 8])
print(val)

Output:

[1.e+27 1.e+08]

3. Log-Sum Exponential Function

The scipy.special.logsumexp() function is used to calculate the logarithmic value of the sum of the exponents of the input elements.

Example:

from scipy.special import logsumexp
import numpy as np
inp = np.arange(5)
val = logsumexp(inp)
print(val)

Here, numpy.arange() function is used to generate a sequence of numbers to be passed as input.

Output:

4.451914395937593

4. Gamma Function

Gamma function is used to calculate the gamma value, referred to as generalized factorial because, gamma(n+1) = n!

The scipy.special.gamma() function is used to calculate the gamma value of the input element.

Example:

from scipy.special import gamma
val = gamma([5, 0.8, 2, 0])
print(val)

Output:

[24.          1.16422971  1.                 inf]

Interpolation Functions

Interpolation is a process to find values between two or more points on a curve, line, etc.

The scipy.interpolate package is used to perform interpolation on a particular graph.

Example:

import numpy as np
from scipy import interpolate
import matplotlib.pyplot as p
a = np.linspace(0, 4, 12)
b = np.sin(x**2/3+4)
print(a,b)
p.plot(a, b, 'o') # Plotting the graph assuming a and b arrays as x and y dimensions
p.show()

In the above snippet of code, we have created a sine wave, and have plotted the values using Python PyPlot package of Matplotlib Module.

Output:

[0.         0.36363636 0.72727273 1.09090909 1.45454545 1.81818182
 2.18181818 2.54545455 2.90909091 3.27272727 3.63636364 4.        ] [-0.7568025  -0.78486887 -0.85971727 -0.9505809  -0.9999744  -0.92508408
 -0.64146657 -0.12309271  0.51220599  0.96001691  0.85056799  0.09131724]
Interpolation With SciPy
Interpolation With SciPy

Conclusion

Thus, in this article, we have understood the functions served by the Python SciPy library.


References

Recommended read: Python Matplotlib Tutorial and Python NumPy