0% found this document useful (0 votes)
24 views60 pages

Unit Vi

Uploaded by

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

Unit Vi

Uploaded by

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

UNIT – VI

Contents
 Working with NumPy/PlotPy/SciPy
 GUI Programming
Introduction
Tkinter programming
Tkinter widgets
Numpy
Numpy: NumPy stands for Numerical Python. NumPy is a Python
library used for working with arrays.
Numpy arrays
Array are by default Homogeneous, which means data inside an array
must be of the same Data type.
Element wise operation is possible.
Numpy array has the various function, methods, and variables, to ease
our task of matrix computation.
Elements of an array are stored contiguously in memory.
Lists
The list can be homogeneous or heterogeneous.
Element wise operation is not possible on the list.
Python list is by default 1 dimensional. But we can create an N-
Dimensional list. But then too it will be 1 D list storing another 1D list
Elements of a list need not be contiguous in memory.
Advantages of using Numpy Arrays Over Python Lists:
consumes less memory.
fast as compared to the python List.
convenient to use.
Numpy: We can create a N-dimensional array or ndarray in python using
numpy.if n=1,it represents a 1-D.if n=2, it represents a 2-D
To work with numpy,we shoud first import numpy module into our python
programs as
import numpy
Create arrays using numpy: Creating arrays in numpy can be done in several
ways
1.array():used to create an array. When we create an array, we can specify the
data type of the elements either as int or float
array(lst,datatype)
2.linspace():used to create an array with evenly spaced points between a
starting point and ending point
linespace(start,stop,n)
3.logspace() used to create an array with evenly spaced points on a
logarithmically spaced scale
logspace(start,stop,n)
4.arange(): it is same as range()
arange(start,stop,n)
5.zeros() and ones(): zeros(n ,datatype) ones(n ,datatype)
Example program for numpy arrays
Array Creation
We can create an array from a regular Python list or tuple using
the array function. The type of the resulting array is deduced from the
type of the elements in the sequences.
EX:
>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype # dtype('int64')
>>> b = np.array([1.2, 3.5, 5.1])
>>> b.dtype #dtype('float64')
 The type of the array can also be explicitly specified at creation time:
>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])
>>>x=np.random.randint(25,size=5)
>>> print(x) #[22 3 3 20 13]
y=np.random.randint(25,size=(2,3))
>>> print(y) [[22 5 15]
[23 20 17]]
a=np.random.random(5)
>>> print(a)
[0.67999849 0.38306902 0.27780021 0.23773046 0.31309768]
a=np.random.rand(5)
>>> print(a)
[0.70853614 0.10300682 0.9116366 0.96958943 0.8047125 ]
>>> b=np.random.rand(3,3)
>>> print(b) [[0.01900014 0.04698812 0.93412765]
[0.10188628 0.89378112 0.19157245]
[0.04150709 0.20763919 0.31780102]]
>>> c = np.arange(24).reshape(2,3,4) >>> print(c) [[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
Mathematical functions in numpy
The attributes of an ndarray object are:
ndarray.ndim
The number of axes (dimensions) of the array.
ndarray.shape
The dimensions of the array. This is a tuple of integers indicating
the size of the array in each dimension. For a matrix with nrows
and m columns, shape will be (n,m). The length of the shape tuple is
therefore the number of axes, ndim.
ndarray.size
The total number of elements of the array. This is equal to the
product of the elements of shape.
ndarray.dtype
An object describing the type of the elements in the array. One
can create or specify dtype’s using standard Python types. Additionally
NumPy provides types of its own. numpy.int32, numpy.int16, and
numpy.float64 are some examples.
ndarray.itemsize
The size in bytes of each element of the array. For example, an
array of elements of type float64 has itemsize 8 (=64/8), while one of
type complex32 has itemsize 4 (=32/8). It is equivalent
to ndarray.dtype.itemsize.
ndarray.nbytes
The nbytes attribute gives the total number of bytes occupied by
an array
Reshape():
It is useful to change the shape of an array
Flatten()
It is useful to return a copy of the array collapsed into one dimension
Example program
Working with multidimensional arrays:
The 2D arrays ,3D arrays etc. are called multi dimensional arrays
We can create multi dimensional arrays in the following ways.
1.array():is used to create a multidimensional array
a=np.array([[1,2,3,4],[5,6,7,8]])
2.Ones() and zeros() :is used to create a 2D array with several rows
and columns where all the elements we be taken as 1
ones((r,c),dtype)
3.eye(): is used to create 2D array and fills the elements in the
diagonal with 1s
eye(n,dtype=datatype)
4.reshape():is used to convert a 1D array inta a multidimensional
array
reshape(arrayneme,(n,r,c)
Example program

>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021, 0.34556073, 0.39676747], [ 0.53881673, 0.41919451,
0.6852195 ]])
a=n.random.uniform(1,10,(2,3))
>>> a
array([[7.87018937, 2.59528566, 2.05582759],
[5.81273552, 3.04833065, 2.45357191]])
Example program
plotpy
 pyplot is one of the most popular Python packages used for data
visualization. It is a cross-platform library for making 2D plots from data
in arrays. It can be used in python scripts, shell, web application servers
and other graphical user interface toolkits.
pyplot provides a procedural interface to the matplotlib object-oriented
plotting library. It is modeled closely after Matlab.
 The majority of plotting commands in pyplot have Matlab
analogs with similar arguments. Important
commands are explained with interactive examples.
There are various plots which can be created using pyplot. Some of
them are listed below
Plot ,Bar graphs, Histograms, Scatter plot and Pie charts
Plot:The plot() function draws a line from point to point.
Bar graph: A bar graph uses bars to compare data among different
categories. It is well suited when you want to measure the changes
over a period of time. It can be represented horizontally or vertically.
Scatter plot:we need scatter plots in order to compare variables, for
example, how much one variable is affected by another variable to
build a relation out of it.
Histograms are used to show a distribution whereas a bar chart is used
to compare different entities. Histograms are useful when you have
arrays or a very long list.
Pie charts
A pie chart refers to a circular graph which is broken down into segments
i.e. slices of pie. It is basically used to show the percentage or
proportional data where each slice of pie represents a category.
EX 1:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10)
plt.plot(x, x**2, 'r+')
plt.show()
Output:
EX 2:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 1000)
plt.plot(x, np.sin(x), "r+")
plt.plot(x, np.cos(x), "g-")
plt.show()
Output
Ex 3: semilogx(*args, **kwargs)Plot curves with logarithmic x-axis scale

import matplotlib.pyplot as plt


import numpy as np
x = np.linspace(-5, 5, 1000)
plt.semilogx(x, np.sin(12*x), "g-")
plt.show()

Output
Ex 4 semilogy(*args, **kwargs)Plot curves with logarithmic y-axis scale

import matplotlib.pyplot as plt


import numpy as np
x = np.linspace(-5, 5, 1000)
plt.semilogy(x, np.sin(12*x), "g-")
plt.show()

Output
Ex 5:

import matplotlib.pyplot as plt


import numpy as np
x = np.linspace(-5, 5, 1000)
plt.errorbar(x, -1+x**2/20+.2*np.random.rand(len(x)), x/20)
plt.show()

Output
Ex 6 Plot 1-D histogram

import matplotlib.pyplot as plt


from numpy.random import normal
data = normal(0, 1, (2000, ))
plt.hist(data)
plt.show()

Output
Ex 7
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 1000)
img = np.fromfunction(lambda x, y: np.sin((x/200.)*(y/200.)**2), (1000,
1000))
plt.gray()
plt.imshow(img)
plt.show()
Output
Ex 8 Create a pseudocolor plot of a 2-D array

import matplotlib.pyplot as plt


import numpy as np
r = np.linspace(1., 16, 100)
th = np.linspace(0., np.pi, 100)
R, TH = np.meshgrid(r, th)
X = R*np.cos(TH)
Y = R*np.sin(TH)
Z = 4*TH+R
plt.pcolor(X, Y, Z)
plt.show()
scipy
 SciPy is a free and open-source Python library used for scientific
computing and technical computing.
 SciPy contains modules for optimization, linear algebra,
integration, special functions, FFT, signal and image processing, solvers
and other tasks common in science and engineering.
 SciPy builds on the Numpy array object and is part of the Numpy
stack which includes tools like Matplotlib, pandas and SymPy, and an
expanding set of scientific computing libraries.
scipy is composed of task-specific sub-modules
scipy.cluster Vector quantization / Kmeans
scipy.constants Physical and mathematical constants
scipy.fft 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
Special Functions:
SciPy provides a number of special functions that are used in
mathematical physics such as elliptic, convenience functions, gamma,
beta, etc.
Example:
from scipy.special import *
cb = cbrt([8, 125])
print(cb)
com = comb(5, 2)
print(com)
per = perm(5, 2)
print(per)
c = sindg(90)
print(c)
d = cosdg(45)
print(d) [2. 5.]
10.0
20.0
1.0
Integration Functions:
SciPy provides a number of functions to solve integrals.
Ex:
from scipy import integrate
a = lambda y, x: x*y**2
b = lambda x: 1
c = lambda x: -1
integrate.dblquad(a, 0, 2, b, c)

Optimization Functions:
The scipy.optimize provides a number of commonly used optimization
algorithms
Ex:
import numpy as np
from scipy.optimize import rosen
a = 1.2 * np.arange(5)
rosen(a)
Output:
7371.0399999999945
Interpolation Functions:
Interpolation refers to constructing new data points within a set of known data
points.
Ex:
from scipy import interpolate
import numpy as np
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
Fourier Transform Functions:
Fourier analysis is a method that deals with expressing a function as a sum of
periodic components and recovering the signal from those components.
The fft functions can be used to return the discrete Fourier transform of a real
or complex sequence.
Ex:
from scipy.fftpack import fft, ifft
x = np.array([0,1,2,3])
y = fft(x)
print(y)
io module SciPy has many modules, classes, and functions available to
read data from and write data to a variety of file formats.

EX
import numpy as np
from scipy import io as spio
a = np.ones((3, 3))
spio.savemat('file.mat', {'a': a})
data = spio.loadmat('file.mat')
print(data['a'])
Output

[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
scipy.ndimage is a submodule of SciPy which is mostly used for
performing an image related operation
EX
import scipy
from scipy import misc
import matplotlib.pyplot as plt
face=scipy.misc.face()
print(face.shape)
print(face.max())
print(face.dtype)
plt.gray()
plt.imshow(face)
plt.show()

Output
(768, 1024, 3)
255
uint8
import scipy
from scipy import ndimage,misc
import matplotlib.pyplot as plt
face=misc.face(gray=True)
shifted_face = ndimage.shift(face, (50, 50))
plt.figure(figsize=(15, 3))
plt.subplot(151)
plt.imshow(shifted_face,cmap=plt.cm.gray)
plt.show()

Output
GUI Programming
Introduction
 A person who interacts with a software or application is called
a user.
 Two ways for a user to interact with any application.
 Character User Interface
The user gives some commands to perform the work
 Graphical User Interface
The user interacts with an application through Graphics or
pictures or images.
Advantages of GUI
 User friendly
 It adds attraction and beauty to any application by adding pictures,
colors, menus, animations etc.
 possible to simulate the real life objects.
 It helps to create graphical components like push button, radio
button, check button etc.
Tkinter programming
 Python offers Tkinter module to create graphics programs
 Tkinter represents toolkit interface for GUI
 We can enable the interface by using the classes of Tk module of
TCL/TK language(Tool command Language).
 TCL is a dynamic programming language suitable for web and
desktop applications, networking, administration, testing etc.
The following steps are involved in basic GUI programs
 We should create the root window. The root window is the top level
window provides rectangular space on the screen where we display
text, colors, images, components etc.
 In the root window , the space allocation is done by Frame or
canvas. These are child windows of root window.
 We use canvas for displaying drawings like lines, arcs, circles, shapes
etc.
 The frame is used for displaying components like push buttons,
check buttons, menus etc. These are called widgets.
Root window
 To display the graphical output , the space is allocated to any GUI
program called top level window or root window.
 We can reach this root window by creating an object to the class.
 The root window will have a title bar that contains minimize, resize
and close options.
EX
# creating root window
from tkinter import *
root = Tk()
root.title(“my window”)
root.geometry(“400x300”)
root.mainloop()
Canvas: This is a container which is used to draw shapes like lines, curves ,arcs and
circles
c=Canvas(master , option=value…..)
from tkinter import *
w1=Tk()
c=Canvas(w1,bg="blue",height=700,width=1200,cursor="pencil")
id=c.create_line(50,50,200,50,200,150,width=4,fill="white")
id=c.create_oval(100,100,400,300,width=5,fill="yellow",outline="red",activefill="gree
n")
id=c.create_polygon(10,10,200,200,300,200,width=3,fill="green",outline="red",
smooth=1,activefill="lightblue")
id=c.create_rectangle(500,200,700,600,width=2,fill="gray",outline="black",
activefill="yellow")
fnt=("Times",40,"bold italic underline")
id=c.create_text(500,100,text="My canvas",font=fnt,fill="yellow",
activefill="green")
c.pack()
w1.mainloop()
Frame:This is a container which is used to display widgets like buttons,checkbuttons
or menu
f=Frame(master,option=value,-----)
Button: It is used to display buttons in your application
b=Button(master, text=“submit”, command=function,option=value,…….)

from tkinter import *


def Clickme(self):
print("you have clicked me")
w=Tk()
f=Frame(w,height=200,width=300).pack()
b=Button(f,text="My Button",width=15,height=2,bg="yellow",fg="blue",
activebackground="green",activeforeground="red“, command=Clickme())
w.mainloop()
Widgets: A widget is aGUI component that is displayed on the
screen and can perform a task as desired by the user. We create
widgets as objects.

1. Button
2. Label
3. Checkbutton
4. Radiobutton
5. Entry
6. Spinbox
7. Listbox
8. Text
9. Message
10. Scrollbar
11. Menu
Layout Management: once we create widgets or components, we can arrange
them in the frame in a particular manner. Arranging the widgets in the frame is
called layout management. There are three types of layout managers.

1.Pack layout manager: It uses pack() method which associate a widget with its
parent component. While using the pack() method, we can mention the position of the
widget using fill or side options. The fill option can take the values X,
Y,BOTH,NONE. The value X represents that the widget should occupy the frame
horizontally, The value Y represents that the widget should occupy the frame
vertically. Both represents that the widget should occupy the frame horizontally. The
option side which is used to place the widgets side by side.’ side ‘ can take the values
LEFT,RIGHT,TOP or BOTTOM. The default value is TOP
b1.pack(side=Left)
b1.pack(fill=x)
2.Grid layout manager :It uses the grid() method to arrange the widgets in a
two dimensional table that contains rows and columns. The position of a
widget is defined by a row and column number
b.grid(row=0,column=0)
3.Place layout manager: It uses the place() method to arrange the widgets.The
position of the widget is defined by x and y coordinates
b1.place(x=10,y=80)
Label :The Label widget is used to provide a single-line caption for other widgets. It
can also contain images.
l1=Label(master , text=“ hello", option=value,….)

from tkinter import *


class MyButtons:
def __init__(self,w):
self.b1=Button(w,text="ClickMe“,width=15,height=2,command=self.buttonClick)
self.b2=Button(w,text="close",width=15,height=2,command=w.destroy)
self.b1.grid(row=0,column=1)
self.b2.grid(row=0,column=2)
def buttonClick(self):
self.lbl=Label(w,text="welcometopython",width=20,height=2,
font=("Courier",-30,"bold underline"),fg="blue")
self.lbl.grid(row=2,column=0)
w=Tk()
mb=MyButtons(w)
Checkbutton:The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.
c= Checkbutton(master , text=‘submit ’, variable=var1,command=function ,
option=value……)
from tkinter import *
class Mycheck:
def __init__(self,w):
self.var1=IntVar()
self.var2=IntVar()
self.var3=IntVar()
self.c1=Checkbutton(w, text="Java“, variable=self.var1,command= self.display)
self.c2=Checkbutton(w,text=".NET“,variable=self.var2,command= self.display)
self.c3=Checkbutton(w,text="python",variable=self.var3,command= self.display)
self.c1.place(x=50,y=100)
self.c2.place(x=200,y=100)
self.c3.place(x=350,y=100)
def display(self):
x=self.var1.get()
y=self.var2.get()
z=self.var3.get()
str=''
if x==1:
str+="Java"
if y==1:
str+=".NET"
if z==1:
str+="python"
lbl=Label(text=str,fg="blue").place(x=50,y=150,width=200,height=20)
w=Tk()
mb=Mycheck(w)
w.mainloop()
Radiobutton :The Radiobutton widget is used to display a number of options as radio
buttons. The user can select only one option at a time.
r= Radiobutton( master, text=“option1”,variable=z , value=1,command=fun,…..)
from tkinter import *
class Myradio:
def __init__(self,w):
self.var=IntVar()
self.r1= Radiobutton(w,text="Male“, variable=self.var ,value=1,command= self.display)
self.r2= Radiobutton(w,text="Female“ , variable=self.var ,value=2,command=self.display)
self.r1.place(x=50,y=100)
self.r2.place(x=200,y=100)
def display(self):
x=self.var.get()
str=''
if x==1:
str+="you selected:Male"
if x==2:
str+="you selected:Female"
lbl=Label(text=str,fg="blue").place(x=50,y=150,width=200,height=20)
w=Tk()
mb=Myradio(w)
w.mainloop()
Entry :The Entry widget is used to display a single-line text field for accepting values from a
user.
e=Entry(master , option=value,….)
Spin box: It allows the user to select the values from a given set of values. The values may
be a range of numbers or a fixed set of strings
S= Spinbox (master , from_=4,to=15,textvariable= var, command=fun,……..)
S= Spinbox (master , values=(‘a’,’b’,’c’),textvariable= var, command=fun,……..)
List box:It displays a list of items in a box so that the user can select one or more items

l1= Listbox (master ,selectmode=“multiple”,.. …)


Message: It is used to display multiple lines of text
m=Message(master,text=str1,option=value1,…….)
Text : It is same as a label or message and used to display multiple lines of text in different
colors and fonts.
T=Text(master,option=value,……….)
Scrollbar: The Scrollbar widget is used to add scrolling capability to various widgets, such
as list boxes.
s=Scrollbar(master,option=value,……)
Menu: It is used to create all kinds of menus used by the application.
m=Menu(master,option=value,……..)

You might also like