Sunday, March 10, 2019

SciPy - 3 (solving ordinary differential equations)

SciPy provides two different ways to solve ODEs: An API based on the function odeint, and object-oriented API based on the class ode. Usually odeint is easier to get started with, but the ode class offers some fi ner level of control. To solve an ordinary differential equation of the type-



with a given y(t0) = y0 we can use scipy's odeint function. The following program (useodeint.py) to find y(t) for t 2 [0; 2] given this differential equation:



See the code below:

from scipy . integrate import odeint
import numpy as N
def f(y, t):
    """ this is the rhs of the ODE to integrate , i.e. dy/dt=f(y,t)"""
    return -2 * y * t
y0 = 1 # initial value
a = 0 # integration limits for t
b = 2
t = N. arange (a, b, 0.01) # values of t for
# which we require
# the solution y(t)
y = odeint (f, y0 , t) # actual computation of y(t)
import pylab # plotting of results
pylab . plot (t, y)
pylab . xlabel ('t'); pylab . ylabel ('y(t)')
pylab . show ()


The output of the program is as shown below:



The odeint command takes a number of optional parameters to change the default error tolerance
of the integration (and to trigger the production of extra debugging output).  Here we have used the odeint functions. For more information about the class ode, try help(ode). It does pretty much the same thing as odeint, but in an object-oriented fashion.

ODE problems are important in computational physics, so we will look at one more example: the damped harmonic oscillation.

Damping is an influence within or upon an oscillatory system that has the effect of reducing, restricting or preventing its oscillations. In physical systems, damping is produced by processes that dissipate the energy stored in the oscillation. Examples include viscous drag in mechanical systems, resistance in electronic oscillators, and absorption and scattering of light in optical oscillators. Damping not based on energy loss can be important in other oscillating systems such as those that occur in biological systems and bikes.


The damping ratio is a dimensionless measure describing how oscillations in a system decay after a disturbance. Many systems exhibit oscillatory behavior when they are disturbed from their position of static equilibrium. A mass suspended from a spring, for example, might, if pulled and released, bounce up and down. On each bounce, the system tends to return to its equilibrium position, but overshoots it. Sometimes losses (e.g. frictional) damp the system and can cause the oscillations to gradually decay in amplitude towards zero or attenuate. The damping ratio is a measure describing how rapidly the oscillations decay from one bounce to the next.

The damping ratio is a system parameter, denoted by ζ (zeta), that can vary from undamped (ζ = 0), underdamped (ζ < 1) through critically damped (ζ = 1) to overdamped (ζ > 1).

The behaviour of oscillating systems is often of interest in a diverse range of disciplines that include control engineering, chemical engineering, mechanical engineering, structural engineering, and electrical engineering. The physical quantity that is oscillating varies greatly, and could be the swaying of a tall building in the wind, or the speed of an electric motor, but a normalised, or non-dimensionalised approach can be convenient in describing common aspects of behavior.

The equation of motion for the damped oscillator is:



where x is the position of the oscillator, ω0 is the frequency, and ζ is the damping ratio. To write this
second-order ODE on standard form we introduce p = dx/dt :



In the implementation of this example we will add extra arguments to the RHS function for the ODE,
rather than using global variables as we did in the previous example. As a consequence of the extra arguments to the RHS, we need to pass an keyword argument args to the odeint function. See the following code:

from scipy . integrate import odeint
import numpy as N
from matplotlib import pyplot as plt

def dy(y, t, zeta, w0):
    """
    The right-hand side of the damped oscillator ODE
    """
    x, p = y[0], y[1]
    dx = p
    dp = -2 * zeta * w0 * p - w0**2 * x
    return [dx, dp]

# initial state:
y0 = [1.0, 0.0]

# time coodinate to solve the ODE for
t = N.linspace(0, 10, 1000)
w0 = 2*N.pi*1.0

# solve the ODE problem for three different values of the damping ratio
y1 = odeint(dy, y0, t, args=(0.0, w0)) # undamped
y2 = odeint(dy, y0, t, args=(0.2, w0)) # under damped
y3 = odeint(dy, y0, t, args=(1.0, w0)) # critial damping
y4 = odeint(dy, y0, t, args=(5.0, w0)) # over damped

fig, ax = plt.subplots()
ax.plot(t, y1[:,0], 'k', label="undamped", linewidth=0.25)
ax.plot(t, y2[:,0], 'r', label="under damped")
ax.plot(t, y3[:,0], 'b', label=r"critical damping")
ax.plot(t, y4[:,0], 'g', label="over damped")
plt.show()
ax.legend()

In this program we have use matplotlib a mathematical plotting library which is used to make
simple plots, such as line graphs and scatter plots., which we shall discuss separately. The output of the above program is as shown:



Here I am ending this post regarding SciPy solving ordinary differential equations. Next post will discuss about Fourier transforms. Till we meet next keep learning and practicing Python as Python is easy to learn! 



Share:

Thursday, March 7, 2019

SciPy - 2 (scipy.integrate module)

SciPy has a range of different functions to integrate equations and data. Integration is a crucial tool in math and science, as differentiation and integration are the two key components of calculus. Given a curve from a function or a dataset, we can calculate the area below it. In the traditional classroom setting we would integrate a function analytically, but data in the research setting is rarely given in this form, and we need to approximate its definite integral.

Scientifc Python provides a number of integration routines. A general purpose tool to solve integrals
I of the kind


 

is provided by the quad() function of the scipy.integrate module. Numerical evaluation of a function of I type is called numerical quadrature, or simply quadature.

It takes as input arguments the function f(x) to be integrated (the \integrand"), and the lower and upper limits a and b. It returns two values (in a tuple): the first one is the computed results and the second one is an estimation of the numerical error of that result. SciPy provides a series of functions for different kind of quadrature, for example the quad, dblquad and tplquad for single, double and triple integrals, respectively.

The following program shows the integration:

import math
from math import cos , exp , pi
from scipy . integrate import quad

# function we want to integrate
def f(x):
    return exp( math .cos (-2 * x * pi )) + 3.2

# call quad to integrate f from -2 to 2
res , err = quad (f, -2, 2)

print ("The numerical result is {:f} (+ -{:g})". format (res , err ))


We have imported the quad() function from scipy . integrate module. The program solves the integral numerically for . The output of the program is shown below:

The numerical result is 17.864264 (+ -1.55117e-11)
------------------
(program exited with code: 0)

Press any key to continue . . .




The quad() function also takes optional parameters epsabs and epsrel to increase or decrease the accuracy of its computation. The default values are epsabs=1.5e-8 and epsrel=1.5e-8.

Suppose we are given data instead of some known equation and numerical integration is needed.  The figure illustrates what type of data sample can be used to approximate acceptable indefinite integrals. The original function is the line and the randomly sampled data points are shown as dots.



The following program performs the integration:

import numpy as np
from scipy.integrate import quad, trapz

# Setting up fake data
x = np.sort(np.random.randn(150) * 4 + 4).clip(0,5)
func = lambda x: np.sin(x) * np.cos(x ** 2) + 1
y = func(x)
# Integrating function with upper and lower
# limits of 0 and 5, respectively
fsolution = quad(func, 0, 5)
dsolution = trapz(y, x=x)

print('fsolution = ' + str(fsolution[0]))
print('dsolution = ' + str(dsolution))
print('The difference is ' + str(np.abs(fsolution[0] - dsolution)))


The output is as follows:

fsolution = 5.100345067540932
dsolution = 5.1336794982929606
The difference is 0.03333443075202869
------------------
(program exited with code: 0)

Press any key to continue . . . 


The quad integrator can only work with a callable function, whereas trapz is a numerical integrator that utilizes data points.

The next program shows the basic usage of the quad function:

import numpy as np
import math
import scipy.special
from scipy.integrate import quad, dblquad, tplquad


# define a simple function for the integrand
def f(x):
  
    return x

x_lower = 0 # the lower limit of x
x_upper = 1 # the upper limit of x

val, abserr = quad(f, x_lower, x_upper)
print ("integral value =", val, ", absolute error =", abserr)
print('\n')

print("If we need to pass extra arguments to integrand function we can use the args keyword argument\n")

def integrand(x, n):
    """
    Bessel function of first kind and order n.
    """
    return scipy.special.jn(n, x)
  
x_lower = 0 # the lower limit of x
x_upper = 10 # the upper limit of x
val, abserr = quad(integrand, x_lower, x_upper, args=(3,))
print (val, abserr)

#we can use a lambda function (name-less function) instead of explicitly defining a function for the integrand

print("\nUsing `inf' or `-inf' as integral limits\n")

# positive infinity
p_inf = float("inf")
# negative infinity
n_inf = float("-inf")

val, abserr = quad(lambda x: math.exp(-x ** 2), n_inf , p_inf)
print ("numerical =", val, abserr)
analytical = math.sqrt(math.pi)
print ("analytical =", analytical)
print('\n')

print("Passing lambda functions for the limits for the y integration\n")

def integrand(x, y):
    return math.exp(-x**2-y**2)
x_lower = 0
x_upper = 10
y_lower = 0
y_upper = 10
val, abserr = dblquad(integrand, x_lower, x_upper, lambda x : y_lower, lambda x: y_upper)
print (val, abserr)


The output of the program is shown below:

integral value = 0.5 , absolute error = 5.551115123125783e-15


If we need to pass extra arguments to integrand function we can use the args key
word argument

0.7366751370811073 9.389126882496413e-13

Using `inf' or `-inf' as integral limits

numerical = 1.7724538509055159 1.4202636756659625e-08
analytical = 1.7724538509055159


Passing lambda functions for the limits for the y integration

0.7853981633974476 1.3753098510218537e-08


------------------
(program exited with code: 0)


Press any key to continue . . .

In order to understand the above program a basic understanding of Bessel functions, lambda function is required.

Here I am ending this post regarding SciPy integration. Next post will see how to solve an ordinary differential equation. Till we meet next keep learning and practicing Python as Python is easy to learn!












Share:

Wednesday, March 6, 2019

SciPy - 1 (Introduction)

SciPy is a package that utilizes NumPy arrays and manipulations to take on standard problems that scientists and engineers commonly face: integration, determining a function’s maxima or minima, finding eigenvectors for large sparse matrices, testing whether two distributions are the same, and much more.

The optimization package in SciPy allows us to solve minimization problems easily and quickly. For example, performing linear regression, finding a function’s minimum and maximum values, determining the root of a function, and finding where two functions intersect. To install SciPy use:

pip install Scipy 

The SciPy framework builds on top of the low-level NumPy framework for multidimensional arrays, and provides a large number of higher-level scienti c algorithms. Some of the topics that SciPy covers are:

• Special functions (scipy.special)
• Integration (scipy.integrate)
• Optimization (scipy.optimize)
• Interpolation (scipy.interpolate)
• Fourier Transforms (scipy. tpack)
• Signal Processing (scipy.signal)
• Linear Algebra (scipy.linalg)
• Sparse Eigenvalue Problems (scipy.sparse)
• Statistics (scipy.stats)
• Multi-dimensional image processing (scipy.ndimage)
• File IO (scipy.io)

Each of these submodules provides a number of functions and classes that can be used to solve problems in their respective topics.

In the coming posts we will look at how to use some of these subpackages. To access the SciPy package in a Python program, we start by importing everything from the scipy module.

from scipy import *

If we only need to use part of the SciPy framework we can selectively include only those modules we are interested in. For example, to include the linear algebra package under the name la, we can do:

import scipy.linalg as la

The scipy package provides information about its own structure when we use the help command:

>>> help ( scipy )

I am only showing a part of the output of this command:

stats --- Statistical Functions [*]
sparse --- Sparse matrix [*]
lib --- Python wrappers to external libraries [*]
linalg --- Linear algebra routines [*]
signal --- Signal Processing Tools [*]
misc --- Various utilities that don 't have another home .
interpolate --- Interpolation Tools [*]
optimize --- Optimization Tools [*]
cluster --- Vector Quantization / Kmeans [*]
fftpack --- Discrete Fourier Transform algorithms [*]
io --- Data input and output [*]
integrate --- Integration routines [*]
lib. lapack --- Wrappers to LAPACK library [*]
special --- Special Functions [*]
lib. blas --- Wrappers to BLAS library [*]

[*] - using a package requires explicit import (see pkgload )

If we are looking for an algorithm to integrate a function, we might explore the integrate package:

>>> import scipy . integrate
>>> help ( scipy . integrate )

SciPy provides implementations of a very extensive set of special functions which are important for many computational physics problems. Many of the numerical algorithms available through scipy and numpy are provided by established compiled libraries which are often written in Fortran or C. They will thus execute much faster than pure Python code (which is interpreted). As a rule of thumb, we expect compiled code to be two orders of magnitude faster than pure Python code.

Scipy is built on numpy. All functionality from numpy seems to be available in scipy as well. For
example, instead of

import numpy
x = numpy . arange (0, 10, 0.1)
y = numpy .sin(x)

we can therefore also use

import scipy as s
x = s. arange (0, 10, 0.1)
y = s.sin(x)

Here I am ending this introductory post regarding SciPy. Next post will explore the integrate package. Till we meet next keep learning and practicing Python as Python is easy to learn! 
Share:

Tuesday, March 5, 2019

NumPy library - 9 (Reading and Writing Array Data on Files)

The process of reading data contained in a file a very common data analysis operation, since the size of the dataset to be analyzed is almost always huge, and therefore it is not advisable or even possible to manage it manually. NumPy provides a set of functions that allow data analysts to save the results of their calculations in a text or binary file. Similarly, NumPy allows us to read and convert written data in a file into an array.

Lets look into some of the functions:

1. The save() function

In order to save the array we call the save() function and specify as arguments the name of the file and the array. Suppose we have an array 'darray' that contains the results of our data analysis processing we can save it as shown in the following program:

import numpy as np

darray = np.random.random(9).reshape(3,3)

print('The result of analysis is in this array : \n')
print(darray)

np.save('result_DA',darray)

print('\nThe array is saved in your working directory')



The file result_DA.npy will be stored in your working directory. The .npy extension is automatically given to the file. The output of the above program only prints the created array:

The result of analysis is in this array :

[[0.27533037 0.50859006 0.97846682]
 [0.35034065 0.47055893 0.11045708]
 [0.55527203 0.37309907 0.31417643]]

The array is saved in your working directory
------------------
(program exited with code: 0)

Press any key to continue . . . 


2. The load() function

The data saved using the save() function in the .npy file can be recovered using NumPy's load() function by specifying the filename as the argument. Thus to access data stored in result_DA.npy we can use the load() function as shown below:

import numpy as np

darray_data = np.load('result_DA.npy')

print('The content of data analysis array : \n')
print(darray_data)


The output of the program is shown below:

The content of data analysis array :

[[0.27533037 0.50859006 0.97846682]
 [0.35034065 0.47055893 0.11045708]
 [0.55527203 0.37309907 0.31417643]]
------------------
(program exited with code: 0)

Press any key to continue . . .


3. The genfromtxt() function

This function allows to read data from a text file(.txt,.csv) and insert values into an array. It takes three arguments—the name of the file containing the data, the character that separates the values from each other (in this case is a comma), and whether the data contain column headers.

Let's read data from newcities.txt file which is in my working directory and it's content is shown below:

id,value1,value2,value3
1,123,1.4,23
2,110,0.5,18
3,164,2.1,19


The following program uses genfromtxt() function:

cities_data = np.genfromtxt('newcities.txt',delimiter=',', names=True)

print('The content of file : \n')
print(cities_data)
print(cities_data.dtype)


The output of the program is shown below:

The content of file :

[(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]
[('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]
------------------
(program exited with code: 0)

Press any key to continue . . . 


We get a structured array in which the column headings have become the field names. The genfromtxt() function implicitly performs two loops: the first loop reads a line at a time, and the second loop separates and converts the values contained in it, inserting the consecutive elements created specifically. One positive aspect of this feature is that if some data are missing, the function can handle them.

Lets remove some data from newcities.txt file and save the new file as newcities1.txt file. In our previous program use this new file. The output should be something like this:

The content of file :

[(1., 123., 1.4, 23.) (2., 110., nan, 18.) (3.,  nan, 2.1, 19.)]
[('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]


------------------
(program exited with code: 0)

Press any key to continue . . .


As we can see from the output, the genfromtxt() function replaces the blanks in the file with nan values. The column headings contained in the file can be considered labels that act as indexes to extract the values by column, also by using the numerical indexes we can extract data
corresponding to the rows. as shown in the following program:

cities_data = np.genfromtxt('newcities1.txt',delimiter=',', names=True)

print('\nUsing indexes to extract the values by column : \n')
print(cities_data['id'])
print('\nUsing numerical indexes to extract extract data corresponding to the rows : \n')
print(cities_data[0])


The output of the program is shown below:


Using indexes to extract the values by column :

[1. 2. 3.]

Using numerical indexes to extract extract data corresponding to the rows :

(1., 123., 1.4, 23.)


------------------
(program exited with code: 0)

Press any key to continue . . .


Here I will end this post. We have learned about all the main aspects of the NumPy library and became familiar with a range of features and concepts. In the next post, we begin to introduce a new library, called SciPy.

So until we meet next, keep practicing and learning Python as Python is easy to learn!










Share:

Monday, March 4, 2019

NumPy library - 8 (Structured Arrays)

NumPy's Structured Arrays are much more complex not only in size, but in the structure, when compared to mono-dimensional and two-dimensional arrays. They contain structs or records instead of individual items.

Let us create a structured array consisting of an integer, a character string of length 6 and a Boolean value. This will be a simple array of structs as items in which using the dtype option, we'll specify a list of comma-separated specifiers to indicate the elements that will constitute the struct, along with data type and order. Thus in our case we will specify the three types of data in the dtype option with the right order using the corresponding specifiers. See the following program:

import numpy as np

strarr1 = np.array([(1, 'First', 0.5, 1+2j),(2, 'Second', 1.3,2-2j), (3, 'Third', 0.8, 1+3j)],dtype=('i2, a6, f4, c8'))
print('The created Structured array : \n')
print(strarr1)


The output shows the created Structured array based on struct of items:

The created Structured array :

[(1, b'First', 0.5, 1.+2.j) (2, b'Second', 1.3, 2.-2.j)
 (3, b'Third', 0.8, 1.+3.j)]
------------------
(program exited with code: 0)

Press any key to continue . . .


We can also use the data type explicitly specifying int8, uint8, float16, complex64, and so forth to create a structured array. Let's create the above structured array using explicit data type specification. See the following program:

import numpy as np

strarr1 = np.array([(1, 'First', 0.5, 1+2j),(2, 'Second', 1.3,2-2j), (3, 'Third', 0.8, 1+3j)],dtype=('int16, a6, float32, complex64'))
print('The created Structured array : \n')
print(strarr1) 


The output shows the created Structured array based on struct of items which is the same as in the previous program:

The created Structured array :

[(1, b'First', 0.5, 1.+2.j) (2, b'Second', 1.3, 2.-2.j)
 (3, b'Third', 0.8, 1.+3.j)]
------------------
(program exited with code: 0)

Press any key to continue . . .


To access the rows from a Structured array we have to specify the appropriate reference index as we do for other arrays. The following program shows to to retrieve rows from a Structured array:

import numpy as np

strarr1 = np.array([(1, 'First', 0.5, 1+2j),(2, 'Second', 1.3,2-2j), (3, 'Third', 0.8, 1+3j)],dtype=('int16, a6, float32, complex64'))

print('The created Structured array : \n')
print(strarr1)
print('\nThe first row of Structured array : \n')
print(strarr1[0])
print('\nThe second row Structured array : \n')
print(strarr1[1])
print('\nThe third row Structured array : \n')
print(strarr1[2]) 


The output shows the created Structured array and then prints the rows individually:

The created Structured array :

[(1, b'First', 0.5, 1.+2.j) (2, b'Second', 1.3, 2.-2.j)
 (3, b'Third', 0.8, 1.+3.j)]

The first row of Structured array :

(1, b'First', 0.5, 1.+2.j)

The second row Structured array :

(2, b'Second', 1.3, 2.-2.j)

The third row Structured array :

(3, b'Third', 0.8, 1.+3.j)

------------------
(program exited with code: 0)

Press any key to continue . . .

To Structured array, names are assigned automatically to each item of struct which can be considered as the names of the columns of the array. The names are assigned automatically with an f (which stands for field) and a progressive integer that indicates the position in the sequence.Using them as a structured index, we can refer to all the elements of the same type, or of the same column. See the next program which prints the columns using these names:

import numpy as np

strarr1 = np.array([(1, 'First', 0.5, 1+2j),(2, 'Second', 1.3,2-2j), (3, 'Third', 0.8, 1+3j)],dtype=('int16, a6, float32, complex64'))

print('The created Structured array : \n')
print(strarr1)

print('\nThe columns of Structured array : \n')
print(strarr1['f1'])
print(strarr1['f2'])
print(strarr1['f3'])


The output is as follows:

The created Structured array :

[(1, b'First', 0.5, 1.+2.j) (2, b'Second', 1.3, 2.-2.j)
 (3, b'Third', 0.8, 1.+3.j)]

The columns of Structured array :

[b'First' b'Second' b'Third']
[0.5 1.3 0.8]
[1.+2.j 2.-2.j 1.+3.j]
------------------
(program exited with code: 0)

Press any key to continue . . .

A better approach would be to specify the names with something more meaningful which can be done at the time of array declaration as shown in the following program:

import numpy as np

strarr1 = np.array([(1,'First',0.5,1+2j),(2,'Second',1.3,2-2j),
(3,'Third',0.8,1+3j)],dtype=[(
'id','i2'),('position','a6'),('value','f4'),('complex','c8')])

print('The created Structured array : \n')
print(strarr1)
print(strarr1.dtype)
strarr1.dtype.names = ('id','order','value','complex')
print('\nThe columns of Structured array : \n')
print(strarr1['order'])
print(strarr1['value'])
print(strarr1['complex'])

We defined a tuple of names assigned to the dtype attribute of the structured array and then used the elements to print the columns as shown in the following output:

The created Structured array :

[(1, b'First', 0.5, 1.+2.j) (2, b'Second', 1.3, 2.-2.j)
 (3, b'Third', 0.8, 1.+3.j)]
[('id', '<i2'), ('position', 'S6'), ('value', '<f4'), ('complex', '<c8')]

The columns of Structured array :

[b'First' b'Second' b'Third']
[0.5 1.3 0.8]
[1.+2.j 2.-2.j 1.+3.j]
------------------
(program exited with code: 0)

Press any key to continue . . .

Here I am ending today's post. In the next post we shall further explore NumPy library and discuss about Reading and Writing Array Data on Files. Till we meet next keep practicing and learning Python as Python is easy to learn!
Share:

Sunday, March 3, 2019

NumPy library - 7 (Vectorization and broadcasting)

Vectorization is the absence of an explicit loop during the developing of the code. These loops actually cannot be omitted, but are implemented internally and then are replaced by other constructs in the code. The application of vectorization leads to a more concise and readable code.

Due to vectorization many operations take on a more mathematical expression for example we can multiply two arrays arr1 and arr2 as arr1* arr2 just like normal variables. Two matrices A and B can also be multiplied as A*B.

Vectorization, along with the broadcasting, is the basis of the internal implementation of NumPy. Broadcasting allows an operator or a function to act on two or more arrays to operate even if these arrays do not have the same shape. The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements.



Two arrays can be subjected to broadcasting when all their dimensions are compatible, i.e., the length of each dimension must be equal or one of them must be equal to 1. If neither of these conditions is met, we get an exception that states that the two arrays are not compatible. Thus if the dimensions of two arrays are dissimilar, element-to-element operations are not possible.

The operations on arrays of non-similar shapes is still possible in NumPy and this is where  broadcasting comes in to picture. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.

Broadcasting is possible if the following rules are satisfied:

1. Array with smaller ndim than the other is prepended with '1' in its shape.

2. Size in each dimension of the output shape is maximum of the input sizes in that dimension.

3. An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.

4. If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

Thus a set of arrays is set to be broadcastable if the above rules are satisfied and on of the below mentioned criteria is met:

1. Arrays have exactly the same shape.

2. Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.

3.Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.

Let's understand this with the help of an example:

import numpy as np

arr1 = np.arange(9).reshape(3, 3)
arr2 = np.arange(3)

print('The original array are \n')
print(arr1)

print('\nThe original array are \n')
print(arr2)
print('\nThe addition of array are \n')
print(arr1+arr2)


In this example one of the two arrays is smaller than the other. As seen in the code arr1 is a 3 x 3 array and arr2 is 3 element array. Then as per rules of broadcasting we must add a 1 to each missing dimension. If the compatibility rules are now satisfied, you can apply broadcasting and move to the second rule. For example: 3 x 3 , 3x 1

The rule of compatibility is met. Now we can move to the second rule of broadcasting. This rule explains how to extend the size of the smallest array so that it’s the size of the biggest array, so that the element-wise function or operator is applicable.

The second rule assumes that the missing elements (size, length 1) are filled with replicas of the values contained in extended sizes. When the two arrays have the same dimensions, the values inside may be added together as we did in our program print(arr1+arr2)

The output of the program is shown below:

The original array are

[[0 1 2]
 [3 4 5]
 [6 7 8]]

The original array are

[0 1 2]

The addition of array are

[[ 0  2  4]
 [ 3  5  7]
 [ 6  8 10]]


------------------
(program exited with code: 0)

Press any key to continue . . .


There may be more complex cases in which the two arrays have different shapes and each is smaller than the other only in certain dimensions. See the program below:

import numpy as np

arr1 = np.arange(6).reshape(3, 1, 2)
arr2 = np.arange(6).reshape(3, 2, 1)

print('The original array arr1\n')
print(arr1)

print('\nThe original array arr2 \n')
print(arr2)
print('\nThe addition of array are \n')
print(arr1+arr2)


The two arrays has the following dimensions-  3 x 1 x 2 and 3 x 2 x 1 thus they are compatible and therefore the rules of broadcasting can be applied. After broadcasting  the arrays becomes-

arr1 = [[[0,1], arr2 = [[[0,0],
             [0,1]],            [1,1]],
             [[2,3],            [[2,2],
             [2,3]],            [3,3]],
             [[4,5],            [[4,4],
             [4,5]]]            [5,5]]]

Over the broadcasted arrays we apply the addition operator. The output of the program is shown below:

The original array arr1

[[[0 1]]

 [[2 3]]

 [[4 5]]]

The original array arr2

[[[0]
  [1]]

 [[2]
  [3]]

 [[4]
  [5]]]

The addition of array are

[[[ 0  1]
  [ 1  2]]

 [[ 4  5]
  [ 5  6]]

 [[ 8  9]
  [ 9 10]]]

------------------
(program exited with code: 0)

Press any key to continue . . .

Here I am ending today's post. In the next post we shall further explore NumPy library and discuss about Structured Arrays. Till we meet next keep practicing and learning Python as Python is easy to learn!

Share: