Python's Scientific Library

SciPy, short for Scientific Python, is an open-source library that enhances the capabilities of NumPy, a fundamental Python library for numerical computing. It offers a wide range of modules and functions crucial for advanced scientific computing tasks, building upon and extending NumPy's functionality. SciPy incorporates optimized and additional functions commonly utilized in NumPy and Data Science.

To install SciPy, execute the following command:

pip install scipy

Once SciPy is installed, you can import any modules from within SciPy. Its diverse collection of modules offers a wealth of resources, featuring a variety of tools designed for different applications and tasks. Let's delve into the assortment of modules available in SciPy.

SciPy Constants

SciPy provides a selection of pre-defined scientific constants, which are invaluable tools, particularly in Data Science endeavors.

The scipy.constants module in SciPy categorizes various essential numbers into easily accessible groups. These groups encompass numbers pertinent to physical phenomena (like the speed of light and gravity), properties of subatomic particles (such as atoms and nuclei), and significant mathematical constants (like π and e). For scientific calculations requiring the value of constants such as the speed of light or the mathematical constant π, users can readily access these values without the need to search elsewhere.

To retrieve the mathematical constant π (pi) utilizing the constants module:

from scipy import constants
print(constants.pi)    # Output: 3.141592653589793

Weight

In SciPy's constants module, you can retrieve a range of fundamental constants associated with mass. These constants offer values for the masses of fundamental particles like electrons, protons, and neutrons, along with units such as the atomic mass unit and atomic mass constant. They are applicable in diverse scientific computations, particularly in physics, chemistry, nuclear physics, and related disciplines where accurate mass values are essential for calculations or analysis.

Below are several mass-related constants accessible within the constants module of SciPy:

from scipy import constants
print(constants.atomic_mass)            # 1.6605390666e-27
print(constants.m_u)                    # 1.6605390666e-27
print(constants.electron_mass)          # 9.1093837015e-31
print(constants.proton_mass)            # 1.67262192369e-27
print(constants.neutron_mass)           # 1.67492749804e-27
print(constants.m_n)                    # 1.67492749804e-27
print(constants.m_p)                    # 1.67262192369e-27
print(constants.gram)                   # 0.001
print(constants.metric_ton)             # 1000.0
print(constants.grain)                  # 6.479891e-05
print(constants.lb)                     # 0.45359236999999997
print(constants.pound)                 # 0.4535923699999999
print(constants.oz)                    # 0.028349523124999998
print(constants.ounce)                 # 0.028349523124999998
print(constants.stone)                 # 6.3502931799999995
print(constants.long_ton)              # 1016.0469088
print(constants.short_ton)             # 907.1847399999999
print(constants.troy_ounce)            # 0.031103476799999998
print(constants.troy_pound)            # 0.37324172159999996
print(constants.carat)                 # 0.0002

SI Prefixes for the Metric System

Within SciPy's constants module, you'll encounter the Metric (SI) prefixes, which symbolize different powers of 10 utilized to denote decimal multiples and submultiples of units. These prefixes facilitate the representation of exceedingly large or small quantities in scientific calculations and measurements.

from scipy import constants
print(constants.yotta)    #1e+24
print(constants.zetta)    #1e+21
print(constants.exa)      #1e+18
print(constants.peta)     #1000000000000000.0
print(constants.tera)     #1000000000000.0
print(constants.giga)     #1000000000.0
print(constants.mega)     #1000000.0
print(constants.kilo)     #1000.0
print(constants.hecto)    #100.0
print(constants.deka)     #10.0
print(constants.deci)     #0.1
print(constants.centi)    #0.01
print(constants.milli)    #0.001
print(constants.micro)    #1e-06
print(constants.nano)     #1e-09
print(constants.pico)     #1e-12
print(constants.femto)    #1e-15
print(constants.atto)     #1e-18
print(constants.zepto)    #1e-21

Binary Prefixes

The constants module in SciPy encompasses Binary Prefixes, signifying powers of 2 commonly employed in computing to indicate binary multiples or submultiples of bytes. These prefixes provide a convenient method for articulating data storage capacities within the realm of digital information.

from scipy import constants
print(constants.kibi)    #1024
print(constants.mebi)    #1048576
print(constants.gibi)    #1073741824
print(constants.tebi)    #1099511627776
print(constants.pebi)    #1125899906842624
print(constants.exbi)    #1152921504606846976
print(constants.zebi)    #1180591620717411303424
print(constants.yobi)    #1208925819614629174706176

Angular Measurement

SciPy offers a range of functions and constants for handling angles expressed in radians and degrees. Within the constants module, you'll find crucial angle-related constants such as pi (π), as well as the radian and degree constants, which serve as conversion factors between radians and degrees.

from scipy import constants
print(constants.degree)     #0.017453292519943295
print(constants.arcmin)     #0.0002908882086657216
print(constants.arcminute)  #0.0002908882086657216
print(constants.arcsec)     #4.84813681109536e-06
print(constants.arcsecond)  #4.84813681109536e-06

Temporal Measurement

SciPy offers a variety of constants tailored for time-related calculations.

from scipy import constants
print(constants.minute)      #60.0
print(constants.hour)        #3600.0
print(constants.day)         #86400.0
print(constants.week)        #604800.0
print(constants.year)        #315364000.0
print(constants.Julian_year) #31557600.0

Linear Measurement

Within the constants module, you'll find a plethora of constants associated with length, encompassing conversion factors and fundamental lengths utilized in scientific computations. These constants facilitate the manipulation of diverse length units and enable seamless conversions between them.

from scipy import constants
print(constants.inch)             #0.0254
print(constants.foot)             #0.30479999999999996
print(constants.yard)             #0.9143999999999999
print(constants.mile)             #1609.3439999999998
print(constants.mil)              #2.5399999999999997e-05
print(constants.pt)               #0.00035277777777777776
print(constants.point)            #0.00035277777777777776
print(constants.survey_foot)      #0.3048006096012192
print(constants.survey_mile)      #1609.3472186944373
print(constants.nautical_mile)    #1852.0
print(constants.fermi)            #1e-15
print(constants.angstrom)         #1e-10
print(constants.micron)           #1e-06
print(constants.au)               #149597870691.0
print(constants.astronomical_unit) #149597870691.0
print(constants.light_year)       #9460730472580800.0
print(constants.parsec)           #3.0856775813057292e+16

Pressure Measurement

Within the constants module, you'll discover numerous constants pertinent to pressure. These constants furnish conversion factors between various pressure units and present fundamental pressure values essential for scientific computations.

from scipy import constants
print(constants.atm)         #101325.0
print(constants.atmosphere)  #101325.0
print(constants.bar)         #100000.0
print(constants.torr)        #133.32236842105263
print(constants.mmHg)        #133.32236842105263
print(constants.psi)         #6894.757293168361

Surface Measurement

The constants module contains numerous constants associated with area.

from scipy import constants
print(constants.hectare) #10000.0
print(constants.acre)    #4046.8564223999992

Spatial Capacity

The constants module includes various constants concerning volume.

from scipy import constants
print(constants.liter)            #0.001
print(constants.litre)            #0.001
print(constants.gallon)           #0.0037854117839999997
print(constants.gallon_US)        #0.0037854117839999997
print(constants.gallon_imp)       #0.00454609
print(constants.fluid_ounce)      #2.9573529562499998e-05
print(constants.fluid_ounce_US)   #2.9573529562499998e-05
print(constants.fluid_ounce_imp)  #2.84130625e-05
print(constants.barrel)           #0.15898729492799998
print(constants.bbl)              #0.15898729492799998

Velocity

Within SciPy's constants module, you'll encounter constants associated with speed. These constants offer conversion factors between diverse units of speed and pivotal speed values utilized in scientific computations.

from scipy import constants
print(constants.kmh)            #0.2777777777777778
print(constants.mph)            #0.44703999999999994
print(constants.mach)           #340.5
print(constants.speed_of_sound) #340.5
print(constants.knot)           #0.5144444444444445

​Thermal Measurement

SciPy offers a variety of constants pertaining to temperature.

from scipy import constants
print(constants.zero_Celsius)      #273.15
print(constants.degree_Fahrenheit) #0.5555555555555556

Sparse Data Handling in SciPy

Sparse data denotes datasets or matrices where the majority of elements are zeros compared to the total number of elements. Handling sparse data is essential in scientific computing and data analysis, given its widespread occurrence in fields such as machine learning, scientific simulations, and network analysis.

Scipy incorporates a submodule known as scipy.sparse, which offers functionalities for effectively managing sparse data structures. These structures optimize memory utilization by storing solely the nonzero elements alongside their indices, thereby substantially decreasing storage demands and computational overhead in contrast to storing dense matrices where the majority of values are zeros.

Scipy provides various kinds of sparse matrices, including

* CSC (Compressed Sparse Column): This format stores the sparse matrix by column, utilizing three one-dimensional arrays for each column - one for nonzero values, one for row indices, and another for column pointers.

* CSR (Compressed Sparse Row): Comparable to CSC, this format stores the matrix by rows, enhancing efficiency for row-based operations.

* COO (Coordinate Format): In this format, the sparse matrix is depicted using three arrays that contain the row indices, column indices, and values of nonzero elements.

import numpy as np
from scipy.sparse import csc_matrix
# Creating a dense matrix
dense_matrix = np.array([[0, 0, 3], [4, 0, 0], [0, 5, 6]])
# Converting the dense matrix to a CSC sparse matrix
sparse_matrix_csc = csc_matrix(dense_matrix)
# Accessing elements of the CSC sparse matrix
print("CSC Sparse Matrix:")
print(sparse_matrix_csc)
# Performing operations on the CSC sparse matrix
col_sum = sparse_matrix_csc.sum(axis=0)
print("\nColumn-wise sum of the CSC sparse matrix:")
print(col_sum)

​Result:


Geometric Data in SciPy

Scipy encompasses modules offering capabilities for managing spatial data and conducting diverse spatial operations. Spatial data entails information linked to geographic or spatial locations, frequently employed in geographic information systems (GIS), mapping, and the analysis of spatial relationships.

The scipy.spatial module in SciPy furnishes tools and algorithms tailored for managing and manipulating spatial data. It offers a diverse array of functionalities beneficial for computational geometry, distance calculations, spatial transformations, nearest neighbor computations, and more.

The scipy.spatial module features key components and functionalities, including:

Distance Computations: Scipy provides techniques for calculating distances between points across different dimensions using diverse metrics like Euclidean distance, Manhattan distance, Minkowski distance, and others. This functionality is especially valuable in spatial analysis, clustering, and classification endeavors.

Spatial Convex Hull: This module furnishes algorithms for determining the convex hull of a group of points in space. Convex hulls play a pivotal role in comprehending the shape and configuration of spatial data points.

An example demonstrating the application of certain functionalities within scipy.spatial:

import numpy as np
from scipy.spatial.distance import euclidean, cityblock, minkowski
from scipy.spatial import ConvexHull
# Example of distance calculation between two points 
point1 = (1, 2)
point2 = (4, 6)
# Euclidean distance calculation
euclidean_dist = euclidean(point1, point2)
print(euclidean_dist)              # Output: 5.0
# Manhattan distance calculation
cityblock = cityblock(point1, point2)
print(cityblock)                 # Output: 7
# Minkowski distance calculation
minkowski_dist = minkowski(point1, point2, p=3)
print(minkowski_dist)             # Output: 4.497941445275415
# Computing the convex hull of a set of points
points = np.array([[0, 0], [1, 1], [1, 0], [0, 1]])
hull = ConvexHull(points)
print(hull.vertices)             # Output: [0 2 1 3]

Graph Algorithms in SciPy

Scipy incorporates functionalities for graph and network operations within its https://scipy.sparse.csgraph/ module. This module equips users with tools to efficiently create, manipulate, and analyze graphs.

Some essential functionalities of https://scipy.sparse.csgraph/ for graph operations comprise:

​1. Shortest Path Algorithms: These encompass a range of algorithms designed to calculate the shortest paths between nodes in a graph. Dijkstra's algorithm, Floyd-Warshall algorithm, and Bellman-Ford algorithm are among the available options for determining shortest paths under different conditions.

* Dijkstra's algorithm

The function accepts the following arguments:

return_predecessors: Boolean (True to return the entire traversal path, otherwise False).

indices: The index of the element, returning all paths leading solely to that element.

limit: The maximum weight allowed for the path.

import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
arr =  np.array([
    [0, 4, 0],
    [0, 0, 8],
    [0, 0, 7]])
newarr = csr_matrix(arr)
print(dijkstra(newarr, return_predecessors=True, indices=0))

Output: (array([0., 1., 2.]), array([-9999,     0,     0], dtype=int32))

* The Floyd-Warshall Algorithm

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

Output: (array([[0., 1., 2.], [1., 0., 3.], [2., 1., 0.]]), 

array([[-9999,     0,     0], [    1, -9999,     0],[    2,     2, -9999]], dtype=int32))
Bellman-Ford algorithm
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, 7],
  [2, 1, 3]
])
newarr = csr_matrix(arr)
print(bellman_ford(newarr, return_predecessors=True, indices=0))

Output:  (array([ 0., -1.,  2.]), array([-9999,     0,     0], dtype=int32))

2. Connected Components: Scipy offers functions for identifying connected components within a graph. This is crucial for comprehending the structure and connectivity of networks.

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))

Output: (1, array([0, 0, 0], dtype=int32))

Interpolating Data

In Scipy, interpolation involves estimating values between known data points. For instance, one might interpolate between points 1 and 2 to derive intermediate values such as 1.44 and 1.66.

Scipy offers a range of interpolation methods to efficiently accomplish this task.

The scipy.interpolate submodule encompasses a diverse array of functions and classes designed for interpolation, addressing various data types and needs. Among the commonly employed interpolation methods found in Scipy are:

1. Linear Interpolation (interp1d): This method creates a linear interpolating function between data points, assuming a linear relationship between successive points.

from scipy.interpolate import interp1d
import numpy as np
xs = np.array([1,2,3,4,5,6,7,8,9])
ys = 2*xs + 1
interp_func = interp1d(xs, ys)
newarr = interp_func(np.arange(2.1, 3, 0.1))
print(newarr)

Output: [5.2 5.4 5.6 5.8 6.  6.2 6.4 6.6 6.8]

Spline Interpolation: This technique constructs piecewise cubic polynomials between data points, ensuring smoothness by preserving continuity in the first and second derivatives.

from scipy.interpolate import UnivariateSpline
import numpy as np
xs = np.array([1,2,3,4,5,6,7,8,9])
ys = xs**2 + np.sin(xs) + 1
interp_func = UnivariateSpline(xs, ys)
newarr = interp_func(np.arange(2.1, 3, 0.1))
print(newarr)

Output: [5.62894853 5.9917962  6.37883473 6.78997537 7.22512936   7.68420794   8.16712235 8.67378384 9.20410364]

These modules represent some of the key components offered by SciPy. As a robust and versatile library within Python's scientific computing ecosystem, SciPy provides an extensive range of tools and functions for numerous numerical and scientific tasks. With its powerful capabilities, SciPy streamlines complex computations, empowering researchers, scientists, and developers to address a diverse array of scientific challenges effectively.

What Monkey Patching Is and Its Application in Odoo 17