0% found this document useful (0 votes)
12 views

sci py

The document provides an overview of the SciPy library, detailing its various submodules for scientific computing, such as optimization, integration, and statistics. It includes examples of using SciPy functions for linear algebra operations, finding roots of equations, and curve fitting. Additionally, it highlights the importance of NumPy in conjunction with SciPy for efficient data manipulation.

Uploaded by

wankhade.ojjas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

sci py

The document provides an overview of the SciPy library, detailing its various submodules for scientific computing, such as optimization, integration, and statistics. It includes examples of using SciPy functions for linear algebra operations, finding roots of equations, and curve fitting. Additionally, it highlights the importance of NumPy in conjunction with SciPy for efficient data manipulation.

Uploaded by

wankhade.ojjas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

from google.

colab import files


uploaded = files.upload()

Choose Files college1.png


college1.png(image/png) - 196300 bytes, last modified: 1/16/2025 - 100% done
S i ll 1 t ll 1
 

from IPython.display import Image, display


display(Image(filename='college1.png')) # Replace with your actual filename if different

 

keyboard_arrow_down Scipy Notes


The scipy package contains various toolboxes dedicated to common issues in scientific computing. Its different submodules correspond to
different applications, such as interpolation, integration, optimization, image processing, statistics, special functions, etc.

scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Scientific Library for C and C++), or Matlab’s
toolboxes. scipy is the core package for scientific routines in Python; it is meant to operate efficiently on numpy arrays, so that numpy and
scipy work hand in hand.

scipy is composed of task-specific sub-modules:

scipy.cluster Vector quantization / Kmeans

scipy.constants Physical and mathematical constants

scipy.fftpack Fourier transform

scipy.integrate Integration routines

scipy.interpolate Interpolation

scipy.io Data input and output

scipy.linalg Linear algebra routines

scipy.ndimage n-dimensional image package

scipy.odr Orthogonal distance regression

scipy.optimize Optimization

scipy.signal Signal processing

scipy.sparse Sparse matrices

scipy.spatial Spatial data structures and algorithms


scipy.special Any special mathematical functions

scipy.stats Statistics

They all depend on numpy, but are mostly independent of each other. The standard way of importing Numpy and these Scipy modules is:

import numpy as np
from scipy import stats # same for other sub-modules

The main scipy namespace mostly contains functions that are really numpy functions (try scipy.cos is np.cos). Those are exposed for
historical reasons; there’s no reason to use import scipy in your code.

Start coding or generate with AI.

keyboard_arrow_down Constants in SciPy


As SciPy is more focused on scientific implementations, it provides many built-in scientific constants.

These constants can be helpful when you are working with Data Science.

from scipy import constants

print(constants.pi)

3.141592653589793

Start coding or generate with AI.

keyboard_arrow_down Constant Units


A list of all units under the constants module can be seen using the dir() function.

from scipy import constants

print(dir(constants))

['Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'ConstantWarning', 'G', 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg', 'Stefan

 

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

1e+24
1e+21
1e+18
1000000000000000.0
1000000000000.0
1000000000.0
1000000.0
1000.0
100.0
10.0
0.1
0.01
0.001
1e-06
1e-09
1e-12
1e-15
1e-18
1e-21

from scipy import constants

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.45359236999999997
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
print(constants.atomic_mass) #1.66053904e-27
print(constants.m_u) #1.66053904e-27
print(constants.u) #1.66053904e-27

0.001
1000.0
6.479891e-05
0.45359236999999997
0.45359236999999997
0.028349523124999998
0.028349523124999998
6.3502931799999995
1016.0469088
907.1847399999999
0.031103476799999998
0.37324172159999996
0.0002
1.6605390666e-27
1.6605390666e-27
1.6605390666e-27

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

0.017453292519943295
0.0002908882086657216
0.0002908882086657216
4.84813681109536e-06
4.84813681109536e-06

keyboard_arrow_down Linear algebra operations: scipy.linalg


The scipy.linalg module provides standard linear algebra operations, relying on an underlying efficient implementation (BLAS, LAPACK).

# The scipy.linalg.det() function computes the determinant of a square matrix:

from scipy import linalg


arr = np.array([[1, 2],
[3, 4]])

print(linalg.det(arr))

-2.0

arr_2 = np.array([[3, 2],


[6, 4]])

print(linalg.det(arr_2))

0.0
a=np.ones((3,4))
print(a)

print(linalg.det(a))

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-26-2d0fa98b2af7> in <cell line: 0>()
2 print(a)
3
----> 4 print(linalg.det(a))

/usr/local/lib/python3.11/dist-packages/scipy/linalg/_basic.py in det(a, overwrite_a, check_finite)


1073 raise ValueError('The input array must be at least two-dimensional.')
1074 if a1.shape[-1] != a1.shape[-2]:
-> 1075 raise ValueError('Last 2 dimensions of the array must be square'
1076 f' but received shape {a1.shape}.')
1077

ValueError: Last 2 dimensions of the array must be square but received shape (3, 4).

 

Next steps: Explain error

keyboard_arrow_down The scipy.linalg.inv() function computes the inverse of a square matrix:


arr = np.array([[1, 2],
[3, 4]])
iarr=linalg.inv(arr)
print(iarr)

[[-2. 1. ]
[ 1.5 -0.5]]

np.allclose(np.dot(arr, iarr), np.eye(2))

#Returns True if two arrays are element-wise equal

True

arr = np.array([[3, 2],


[6, 4]]) # this brings singularity hence no inverse.
print(linalg.inv(arr) )

---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-29-8727be865bc0> in <cell line: 0>()
1 arr = np.array([[3, 2],
2 [6, 4]]) # this brings singularity hence no inverse.
----> 3 print(linalg.inv(arr) )

/usr/local/lib/python3.11/dist-packages/scipy/linalg/_basic.py in inv(a, overwrite_a, check_finite)


997 inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
998 if info > 0:
--> 999 raise LinAlgError("singular matrix")
1000 if info < 0:
1001 raise ValueError('illegal value in %d-th argument of internal '

LinAlgError: singular matrix

 

Next steps: Explain error

# solve following equation

# 2x+3y=8
# 5x+7y=19

import numpy as np
from scipy.linalg import solve

# Coefficients matrix
A = np.array([[2, 3], [5, 7]])

# Constants matrix
b = np.array([8, 19])

# Solving for x and y


solution = solve(A, b)
print(f"the value for x is {solution[0]} and y is {solution[1]}:")

the value for x is 1.0 and y is 2.0:

Solving an Overdetermined System (Least Squares Solution)

Solve the system of equations using the least squares method:

x+2y=2

3x+5y=6

6x+8y=9

(Since there are more equations than unknowns, we need to find the best approximate solution.)

from scipy.linalg import lstsq


import numpy as np

# Coefficients matrix
A = np.array([[1, 2], [3, 5], [6, 8]])

# Constants vector
b = np.array([2, 6, 9])

# Solving using least squares


x, residuals, rank, s = lstsq(A, b)

print("Least Squares Solution:\n", x)


print("Residuals:\n", residuals)

print(f'the value of x is {x[0]} and y is {x[1]}')

#This gives the best possible values for x and y that minimize the error.

Least Squares Solution:


[-0.1509434 1.24528302]
Residuals:
0.16981132075471767
the value of x is -0.1509433962264157 and y is 1.2452830188679251

Computing Generalized Eigenvalues Problem: Find the generalized eigenvalues for the matrices:

`𝐴 =[4 2

3 1]`

,𝐵=[1001]

(Generalized eigenvalues satisfy Av=λBv .)

from scipy.linalg import eig

A = np.array([[4, 2], [3, 1]])


B = np.array([[1, 0], [0, 1]])

# Compute generalized eigenvalues


eigvals, eigvecs = eig(A, B)

print("Generalized Eigenvalues:\n", eigvals)


print("Generalized Eigenvectors:\n", eigvecs)

Generalized Eigenvalues:
[ 5.37228132+0.j -0.37228132+0.j]
Generalized Eigenvectors:
[[ 0.82456484 -0.41597356]
[ 0.56576746 0.90937671]]

Start coding or generate with AI.

keyboard_arrow_down Roots of an Equation


NumPy is capable of finding roots for polynomials and linear equations, but it can not find roots for non linear equations, like this one:

x + cos(x)

For that you can use SciPy's optimize.root function.

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:

# Example
# Find root of the equation x + cos(x):

from scipy.optimize import root


import numpy as np

def eqn(x):
return x + np.cos(x)

myroot = root(eqn, 0)

print(myroot.x)

[-0.73908513]

keyboard_arrow_down Optimization and fit: scipy.optimize


Optimization is the problem of finding a numerical solution to a minimization or equality.

The scipy.optimize module provides algorithms for function minimization (scalar or multi-dimensional), curve fitting and root finding.

Curve fitting: temperature as a function of month of the year


We have the min and max temperatures in Alaska for each months of the year. We would like to find a function to describe this yearly
evolution.

For this, we will fit a periodic function.

The data

import numpy as np

temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])

import matplotlib.pyplot as plt


months = np.arange(12)
plt.plot(months, temp_max, 'ro')
plt.plot(months, temp_min, 'bo')
plt.xlabel('Month')
plt.ylabel('Min and max temperature')
Text(0, 0.5, 'Min and max temperature')

 

keyboard_arrow_down Fitting it to a periodic function


from scipy import optimize
def yearly_temps(times, avg, ampl, time_offset):
return (avg
+ ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()))

res_max, cov_max = optimize.curve_fit(yearly_temps, months,


temp_max, [20, 10, 0])
res_min, cov_min = optimize.curve_fit(yearly_temps, months,
temp_min, [-40, 20, 0])

keyboard_arrow_down Plotting the fit


days = np.linspace(0, 12, num=365)

plt.figure()
plt.plot(months, temp_max, 'ro')
plt.plot(days, yearly_temps(days, *res_max), 'r-')
plt.plot(months, temp_min, 'bo')
plt.plot(days, yearly_temps(days, *res_min), 'b-')
plt.xlabel('Month')
plt.ylabel('Temperature ($^\circ$C)')

plt.show()

 
keyboard_arrow_down Finding the minimum of a scalar function
Let’s define the following function:

def f(x):
return x**2 + 10*np.sin(x)

# and plot it:

x = np.arange(-10, 10, 0.1)


plt.plot(x, f(x))
plt.show()

 

This function has a global minimum around -1.3 and a local minimum around 3.8.

Searching for minimum can be done with scipy.optimize.minimize(), given a starting point x0, it returns the location of the minimum that it
has found:

result = optimize.minimize(f, x0=0)


print(result)

message: Optimization terminated successfully.


success: True
status: 0
fun: -7.945823375615215
x: [-1.306e+00]
nit: 5
jac: [-1.192e-06]
hess_inv: [[ 8.589e-02]]
nfev: 12
njev: 6

result.x # The coordinate of the minimum

array([-1.30644012])

Methods: As the function is a smooth function, gradient-descent based methods are good options. The lBFGS algorithm is a good choice in
general:

optimize.minimize(f, x0=0, method="L-BFGS-B")

message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL


success: True
status: 0
fun: -7.945823375615166
x: [-1.306e+00]
nit: 5
jac: [-1.599e-06]
nfev: 12
njev: 6
hess_inv: <1x1 LbfgsInvHessProduct with dtype=float64>

You might also like