Python

Python Menu

SciPy is a scientific computation library that uses NumPy underneath. It stands for Scientific Python. It provides more utility functions for optimization, stats and signal processing.SciPy was created by Travis Olliphant.

Installation of SciPy

If you have Python and PIP already installed on a system, install it using this command:

pip install scipy

Once SciPy is installed, import the SciPy module(s) you want to use in your applications by adding the from scipy import module statement:

from scipy import constants

Unit Categories

The units in SciPy could be under these categories:

  • Metric
  • Binary
  • Mass
  • Angle
  • Time
  • Length
  • Pressure
  • Volume
  • Speed
  • Temperature
  • Energy
  • Power
  • Force

Unit Categories Usage:

Metric (Return the specified unit in meter):

from scipy import constants
print(constants.centi) print(constants.milli)

Binary (Return the specified unit in bytes):

from scipy import constants
print(constants.gibi) print(constants.tebi)

Mass (Return the specified unit in kg):

from scipy import constants
print(constants.pound) print(constants.oz)

Angle (Return the specified unit in radians):

from scipy import constants
print(constants.degree) print(constants.arcsec)

Time (Return the specified unit in seconds):

from scipy import constants
print(constants.hour) print(constants.year)

Length (Return the specified unit in meters):

from scipy import constants
print(constants.yard) print(constants.nautical_mile)

Pressure (Return the specified unit in pascals):

from scipy import constants
print(constants.mmHg) print(constants.psi)

Area (Return the specified unit in square meters):

from scipy import constants
print(constants.hectare) print(constants.acre)

Volume (Return the specified unit in cubic meters):

from scipy import constants
print(constants.liter) print(constants.fluid_ounce)

Speed (Return the specified unit in meters per second):

from scipy import constants
print(constants.mph) print(constants.mach)

Temperature (Return the specified unit in Kelvin):

from scipy import constants
print(constants.zero_Celsius) print(constants.degree_Fahrenheit)

Energy (Return the specified unit in joules):

from scipy import constants
print(constants.eV) print(constants.erg) print(constants.Btu)

Power (Return the specified unit in watts):

from scipy import constants
print(constants.hp) print(constants.horsepower)

Force (Return the specified unit in newton):

from scipy import constants
print(constants.pound_force) print(constants.kgf)

SciPy Optimizers

Roots of an Equation

NumPy is capable of finding roots for polynomials and linear equations, but it can not find roots for nonlinear equations. This function takes two required arguments:

  • fun - a function representing an equation.
  • x0 - an initial guess for the root.

The function returns an object with information regarding the solution. The actual solution is given under attribute x of the returned object:

from scipy.optimize import root from math import cos
def eqn(x): return x + cos(x)
myroot = root(eqn, 0)
print(myroot.x) print(myroot)

Minimizing a Curve

The highest point in the whole curve is called global maxima, while the rest of the high points are called local maxima. The lowest point in the whole curve is called global minima, while the rest of the low points are called local minima.

scipy.optimize.minimize() function can be used to minimize the function.

The minimize() function takes the following arguments:

  • fun - a function representing an equation.

  • x0 - an initial guess for the root.

  • method - name of the method to use. Legal values:

    • 'CG'
    • 'BFGS'
    • 'Newton-CG'
    • 'L-BFGS-B'
    • 'TNC'
    • 'COBYLA'
    • 'SLSQP'
  • callback - function called after each iteration of optimization.

  • options - a dictionary defining extra params:

{
    "disp": boolean - print detailed description
    "gtol": number - the tolerance of the error
}

Example:

from scipy.optimize import minimize
def eqn(x): return x**2 + x + 2
mymin = minimize(eqn, 0, method='BFGS')
print(mymin)

SciPy Graphs

connected_components() method finds all of the connected components in a graph.

import numpy as np from scipy.sparse.csgraph import connected_components from scipy.sparse import csr_matrix
arr = np.array([ [0, 1, 2], [1, 0, 0], [2, 0, 0] ])
newarr = csr_matrix(arr)
print(connected_components(newarr))

dijkstra method finds the shortest path in a graph from one element to another

It takes following arguments:

  • return_predecessors: boolean (True to return whole path of traversal otherwise False).
  • indices: index of the element to return all paths from that element only.
  • limit: max weight of path.
import numpy as np from scipy.sparse.csgraph import dijkstra from scipy.sparse import csr_matrix
arr = np.array([ [0, 1, 2], [1, 0, 0], [2, 0, 0] ])
newarr = csr_matrix(arr)
print(dijkstra(newarr, return_predecessors=True, indices=0))

floyd_warshall() method finds the shortest path between all pairs of elements.

import numpy as np from scipy.sparse.csgraph import floyd_warshall from scipy.sparse import csr_matrix
arr = np.array([ [0, 1, 2], [1, 0, 0], [2, 0, 0] ])
newarr = csr_matrix(arr)
print(floyd_warshall(newarr, return_predecessors=True))

bellman_ford() method also finds the shortest path between all pairs of elements, but this method can handle negative weights as well.

import numpy as np from scipy.sparse.csgraph import bellman_ford from scipy.sparse import csr_matrix
arr = np.array([ [0, -1, 2], [1, 0, 0], [2, 0, 0] ])
newarr = csr_matrix(arr) print(bellman_ford(newarr, return_predecessors=True, indices=0))

depth_first_order() method returns a depth first traversal from a node

This function takes following arguments:

  • the graph
  • the starting element to traverse graph from.
import numpy as np from scipy.sparse.csgraph import depth_first_order from scipy.sparse import csr_matrix
arr = np.array([ [0, 1, 0, 1], [1, 1, 1, 1], [2, 1, 1, 0], [0, 1, 0, 1] ])
newarr = csr_matrix(arr)
print(depth_first_order(newarr, 1))

breadth_first_order() method returns a breadth first traversal from a node.

This function takes following arguments:

  • the graph
  • the starting element to traverse the graph from
import numpy as np from scipy.sparse.csgraph import breadth_first_order from scipy.sparse import csr_matrix
arr = np.array([ [0, 1, 0, 1], [1, 1, 1, 1], [2, 1, 1, 0], [0, 1, 0, 1] ])
newarr = csr_matrix(arr)
print(breadth_first_order(newarr, 1))

SciPy Statistical Significance Tests

ttest_ind() function takes two samples of the same size and produces a tuple of t-statistic and p-value.

import numpy as np from scipy.stats import ttest_ind
v1 = np.random.normal(size=100) v2 = np.random.normal(size=100)
res = ttest_ind(v1, v2) resP = ttest_ind(v1, v2).pvalue print(res) print("P-value = " , resP)

describe() function returns the following description:

  • number of observations (nobs)
  • minimum and maximum values = minmax
  • mean
  • variance
  • skewness
  • kurtosis
import numpy as np from scipy.stats import describe
mydata = np.random.normal(size=100) result = describe(mydata)
print(result)

Normality Tests Based on the Skewness and Kurtosis

import numpy as np from scipy.stats import skew, kurtosis from scipy.stats import normaltest
mydata = np.random.normal(size=100)
print("Skewness = ", skew(mydata)) print("Kurtosis = ", kurtosis(mydata)) print("Normal Test Result = ", normaltest(mydata))

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods