Python Programming Languages
Python Programming Languages
gf 69+
PYTHON
PROG1
RAMMING IANGUAGE-11
Mathematics Practical (MTC-Z43J : Paper-HI
CBCS
2 c.REDIIS
[I] Notes ,t ~ 6 ~f 69+ >>
S\iflabus ...
1. 2D, 3D Graphs
1.1 Installation of numpy, matplotlib packages.
1.2 Graphs plotting of functions such as ... etc.
1.3 Different formats of graphs.
1.3 Three-dimensional Points and Lines.
1.4 Three-dimensional Contour Plots.
1.5 Wireframes and Surface Plots.
1.6 Graphs plotting of functions such as ... etc.
2. Computational Geometry
2.1 Points: The distance between two points, Lists of Points - the Point List class,
Integer points lists, Ordered Point sets, Extreme Points of a Point List, Random sets
of Points not in general position.
2.2 Points: Displaying points and other geometrical objects, lines, rays, and line
segments, The geometry of line segments, Displaying lines, rays and line segments.
2.3 Polygon: Representing polygon in Python, Triangles, Signed area of a triangle,
Triangles and the relationships of points to lines is, collinear, is Left, is Left On, is
Right, is Right On, Between.
2.4 Two dimensional rotation and reflection.
2.5 Three dimensional rotation and reflection.
2.6 Generation of Bezier curve with given control points.
3. Study of Operatlonal Research In Python
3.1 Linear Programming in Python.
3.2 Introduction to Simplex Method in Python.
Notes , ...Q I) >>
Commts
1. 2D, 3D Graphs 1.
1.1 Installation of Numpy and Matplotlib Packages 1
1.1.1 Installation of Numpy and Matplotlib 1
1.2 Graph plotting using Matplotlib 2
1.2.1 Logarithmic functions 2
1.2.2 Trignometric Functions 3
1.2.3 Inverse Trignometric Functions 3
1.2.4 Algebraic Functions 4
1.2.S Exponential Functions 5
1.2.6 General combination of LIATE function 5
1.2.7 Visualising a Three Dimensional Function in Two dimensions 6
1.3 Different formats for Graphs in Python 7
1.3.1 Line Graphs 7
1.3.2 Bar graphs 8
1.3.3 Histogram 9
1.3.4 Pie chart 10
1.3.S Scatter plots 11
1.4 Three dimensional Points and Lines 11
1.5 Three dimensional contour plots 14
1.6 Wireframes and Surface plots 15
1.7 Surface Triangulations 16
1.8 Self Exercises 17
2. Computational Geometry 21
2.1 Points 21
2.1.1 Point class 21
2.1.2 Euclidean distance between points 23
2.1.3 List of points: Point List class 23
2.1.4 Integer Point Lists 26
2.1.5 Ordered Point Sets 26
2.1.6 Extreme Points 27
2.1.7 Random Set of Points not in any General Position 27
2.2 Displaying Points and Other Geometrical Objects 28
2.2.1 Line, Rays and Line Segments 32
2.2.2 Displaying Lines, Rays and Line Segments 34
2.3 Polygons 36
2.3.1 Triangle 37
2.3.2 Signed Area of a triangle 38
2.3.3 Triangles and the relationships of points to the lines 39
2.4 Two dimensional rotation and reflection 40
2.5 Three dimensional rotation and reflection 42
2.6 Bezier Curve with Control Points 44
2.7 Self Exercises 47
3. Study of Operations Research In Python 49
3.1 Linear Programming in Python 49
3.1.1 Basic Terminologies 49
3.2 Introduction to Simplex Method in Python 52
3.3 Self Exercises 54
Chapter 1
2D, 3D Graphs
Note that,
• np. log18() : computes the value of the logarithm to the base 10.
0 6 8 10
• np.arangeQ: is used to plot points in the specified interval with a specified distance
• np.cosO: calculates the cosine of the values on which the interval where it is defined
l OO
07S
oso
0 25
000
--0.25
--0.50
--0 75
- 1.00
0 2 3 4 5 6
3
CHAPTER I. 2D, 3D GRAPHS
S.Y.B.Sc.(Computer Science) Python Programming Language n
Note that,
• np . arcsin() will calculate the values of the inverse sine function for a given set of values.
15
10
0.5
00
-0 5
-1.0
-1.5
1
Fig. 1.3: Plot of the function /(x} = sin- (x)
••
"
30
2.5
,..
IS
LO
.,
00
_, 0 - 1' -l 0 ..,,
Fig. 1.4 : Plot of the function/ (x) = x2
plt.plot(x, y)
plt.show()
Note that
• pl t. figure() creates a plot of the given size. For plot of f {x) = x2 see the Fig. l.4.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, l&&)
y = np.exp(x)
plt.plot(x,y)
plt.sbow()
Note that
- 10 -OS 00 OS 10 15 2.0
· 100
· UO
.,oo
-lSO
-lOO
- )SO
Fig. 1.6 : Plot of the combination LIATE, f (x) = sin x - ex + 3x2 - log 10 x
import numpy as np
import matplotlib.pyplot as plt
plt.style.use( ' seaborn-white')
def f(x, y):
retwn np.sin(x) ** l& + np .cos(5 + y * x) * np.sin(x)
x = np.linspace(&, 5, 5&)
y = np.linspace(&, 5, 5&)
X, Y = np.meshgrid(x, y)
Z = f(X,Y)
plt.contourf(X, Y, Z, 2&, cmap='RdBu')
pl t. colorbar ()
Note that,
• np. meshgrid() is used to construct a grid corresponding to the two given arrays.
• pl t. contour£() is used to construct the contour corresponding to a given function.
00
-<) )
_.,,
Note that,
• plt. xlabel (), pl t. ylabel () is used to label the x-axis and y-axis, respectively.
lJ,O US lSO US
......
100 2-25 lSO 275 300
Pune Murnbl1
.,.,.,
~pur ....,_ Set••
Fig. 1.9 : Bar Graph
1.3.3 Histogram
A histogram is usually used to represent approximate distribution of numerical data. To construct
a histogram the range of values is usually divided in to non-overlapping intervals called as bins.
The number of values corresponding to each bin are noted and bars are drawn corresponding to the
number of values in each bin. The bins must be adjacent and are often equal in sire. As discussed,
it is used to describe numerical data which is given in a set of raw values.
scatter plo<
100
• •
90
• • •
80 • • •
i
JO
•
,)!
r,o
) 50
• • • •
«>
JJ
• •
•
••
20 •
20 «> r,o 80 IDO
Gr-.Rongo
Once this submodule is imported, a three-dimensional axes can be created by passing the
keyword projection=' 3d' to any of the normal axes creation procedure;
import numpy as np
import matplotlib.pyplot as plt
fig= plt.figure()
ax= plt.axes(projection='3d')
10
08
06
04
01
00
1n
Fig. I. 13 : 3D Axes
The basic three dimensional plot is a line or a scaner plot created using (x. y, z) triples. Note
that,
The following code plots lines in 3D connecting points which lie on a circular helix (spring).
Note that the co-ordinates on this helix are given by (sin /, cos I , t) , t ER.
import numpy as np
import matplotlib . pyplot as plt
zvalue = np.linspace(&, 15, 18)
xvalue = np.sin(zvalue)
yvalue = np.cos(zvalue)
ax.plot3D(xvalue, yvalue, zvalue, 'red')
14
u
10
8
6
4
2
0
- 1.Q@~ ~ 26
oq, 2~ sq, 75i_oo
Fig. l.14: 3D Helix
Similarly points in 3D can be plotted. The following examples plots points which lie on a
circular helix (spring). Note that the coordinates on this helix are given by (sin t. cost. t).
import numpy as np
import matplotlib.pyplot as plt
from mpLtoolkits import mplot3d
ax= plt.axes(projection='3d')
zvalue = np.linspace(&, 15, S&)
xvalue = np.sin(zvalue)
yvalue = np.cos(zvalue)
ax.scatter3D(xvalue, yvalue, zvalue, c=zvalue,cmap='Greens')
• • •• 14
u
• • •• '
~
10
8
6
• • •• • 4
2
0
~
-1 °'-~-~2i OQ».2~ sq, 7~oo - 1.
where. - 2 S x ~ 2. -2 ~ y ~ 2.
import numpy as np
import matplotlib . pyplot as plt
from mpl_toolk its import mplot3d
def f (x , y) :
r etunt np.exp(-x**2 - y**2)
x = np.linspac e(- 2, 2, 188)
y = np.linspac e(- 2, 2, 188)
X, Y = np.meshgr id(x, y)
Z = f(X, Y)
fig= plt . figure()
ax= plt.axes(p rojection= ' 3d ' )
ax.contour3D(X, Y, Z, S8 , cmap=' RdBu')
ax.set_xla bel('x')
ax.set_yl abel('y')
ax.set_zl abel('z')
08
06
o•
Q2
-=--=-,,,; f0
8~6
-20..1~1«1-0 -sg y
500 OS 10
I 15 20
-1-5
-20
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def f(x, y):
return np.exp(- x**2 - y**2)
x = np.linspace(- 2, 2, 188)
y = np.linspace(-2, 2, 188)
X, Y = np.meshgrid(x, y)
Z = f(X , Y)
fig= plt.figure()
ax= plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='blue')
ax .set_title('wireframe plot');
w reframe
0.8
06
04
02
-2-0.-15-1.~
soo os 10
15 20
Fig. 1.17: Wireframe plot for f (x,y) = e-(z2+,2)
A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon.
Adding a colormap to the filled polygons can aid perception of the topology of the surface being
visualized.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def f(x, y):
return np.exp(-x**2 - y**2)
x = np.linspace(- 2, 2, 199)
y = np.linspace(-2, 2, 199)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
ax= plt . axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=l, cstride=l,
cmap='viridis', edgecolor='none')
ax.set_title('Gaussian')
Gaussian
08
06
04
02
-2 a_, !°l-111-0
Soo OS LO
LS 20
14
12
IO
8
6
4
2
2 3
0 1
-1
-2
J -3
Fig. 1.19 : Surface Triangulation of / (x , y) "' x2 + y2
(a) /(x) = sio- 1(x + l),x E [-2, 0] (d) / (x) = sinb- 1 x, x E [-10, 10)
(b) /(x) = cos- 1 x {e) /(x) = cosh- x,x 1
E [I , JO]
(c) f(x) = tan- 1 x,x E [-,r/2,n'/21 (f) f (x) = cos- 1 (x2 )
if X ;fa 0
(f) /(x) = {x sin( l /x
2 2
) ~fx ,ta O
(c) f(x) = {~ sin( l /x) 0 if X = 0.
if X = 0.
x2 + 2 if O < X < 5
(d) /(x) = sin(l /x) (g) f (x) = ~ if 5 ~ x < IO
{
smx if x ~ 10 < 15.
18
CHAPTER l. 20, 3D GRAPHS
S.Y.B.Sc.(Computer Science) Python Prograrnmjng Language II
(a)f1(x,y) =l (e) fs (x , y) = 2x + 3y
(b) fi(x,y)=:c (f) f6(X , y) = X2 + y2
□□□
Computational Geometry
2.1 Points
The plane R.2 = R. x R. is referred as the
Euclidean plane. The point refers to posit
Euclidean plane. ion in the
clas s Poin t:
def _ init _(s elf, x=&, y=&):
self . _x = x
self . _y = y
21
def _JIIUl_(self, p) :
return Point(self.x * p.x, self.y * p.y)
def __liash__(self):
return hash((self.x, self.y))
def _iter_(self):
return iter((self. x, self. y))
def _str_(self):
return "({},{})" .format (self.x, self.y)
def __repr_(self):
return "Point({ !r}, { !r})" .format(self.x, self.y)
def roundXY(self):
return Point(round(self.x), round(self.y))
For example one can check the following operations and verify the answers:
ql=Point(16l, 1)
q2=Point(12, 1)
q3=Point (18, 1)
q4=point(18.SS,12.SS)
ql==q3 #this returns true
q2l=q3 #this returns false
ql+q2 #this returns (22,2)
ql~q3 #this returns (188,1)
ro\ll\dXY(l&.SS,12.SS) #this returns (11,13)
import math
def distance(ql, q2):
return math.hypot(q2 . x - ql.x, q2.y - ql .y)
ql=Point(18, 1)
q2=Point(12, 1)
distance(ql,q2) #returns 2
class PointList:
def _init_(self, *args):
if type(args[8]) is Point:
self.points= list(args)
elif type(args[8]) is tuple:
self.points= [Point(t[8], t[l]) fort in args]
elif type(args[8]) is list:
self.points= list(args[8])
else:
raise ValueError("Please check your argments.")
def copy(self):
return copy.deepcopy(self)
def _len_(self):
return len(self.points)
def _iter_(self):
return iter(self.points)
def _ contains_(self, q) :
for pt in self.points:
if pt= q : return True
return False
def roundPoints(self):
return PointList([q.roundXY() for q in self.points])
qll = Poi ntL ist( (l,1 ),(2 ,5), (4,6 ),(7 ,9))
qll
,
• Uthe input is a tuple of objects of the point cJass
Poi ntL ist( Poi nt(4 ,5), Poi nt(l l,8) ,Poi nt(l ,7))
ql 3 = Po in tL ist ([P oi nt ( 4 9 )
, , Po in t(l 9, 8) , Po in t(l ,7 )] )
ql 3
The output is.
Po in tL ist (P oi nt (4 ,5 ) ,P
oi nt (l& ,8 ),P oi nt (l, 7) )
Various other operations can
be perfomed as follows:
ql l.a pp en d( Po in t(S ,8)
)
ql 2. re m ov e( Po in t(l l,8
))
ql 3. re m ov eA ll( (P oi nt
(4 ,5 ),P oi nt (l ,7 )) )
26
CHAPTER 2. COMP\IT
ATIONAL GE OM ETRY
S.Y.B.Sc.(Computer Science) Python Programming Language n
def extremePoints(qlist):
rightex = leftex = topex = bottomex = qlist[8];
for q in qlist:
if (q.x > rightex.x): rightex = q
if (q.y > topex.y): tope.x = q
if (q.x < leftex.x): leftex = q
if (q.y < bottomex.y): bottomex = q
return PointList([rightex, topex, leftex, bottomex])
The above function returns a polnt list. Consider the following example;
extremePoints([Point(-1,-S), Point(2,-2),
Point(-4,-4), Point(2,l), Point(2,2),Point(-S,S),Point(6,6)])
The output will be as follows
PointList(Point(6,6),Point(6,6),Point(- S,5),Point(-1,-5))
2.2 Q=QU{q }
CANVAS_WIDTH=8
CANVASJiEIGHT=8
import matplotl ib.pyplot as plt
class Canvas:
def _init_( self, title, xlabel='X ', ylabel='Y ',
ql=Point (- 8, -8), q2=Point( 8, 8)):
self.fig= plt.figu.re()
self.fig.set_size_inches(CANVAS_WIDTH, CANVASJ{EIGHT)
self.ax= self.fig.ad<Lsubplot(lll, aspect='equal')
plt.ti tle(title)
plt.xlabel(xlabel)
plt. ylabel(ylabel)
plt.xticks(range(ql.x, q2 . x))
plt.yticks(range(ql . y, q2.y))
self.ax.grid(True)
self.ax . set_xlim([ql . x, q2 .x])
self. ax.set_ylim([ql.y , q2.y])
def sbow(self):
plt.show()
plt. clfO
plt.cla()
pl t . close()
And then execute a demo Canvas as follows;
def demoCanvas():
Canvas(title="This is our starting canvas").show()
demoCanvas ()
!j
-_1, 1-
jj
Fig. 2. 1 : Canvas
The above functio n defined will add a circular patch about the given point
of a given radius.
Make sure that the point class is predefined caruer. Refer to the code below;
ql=Po int(8, 8)
gc=Canvas("Filled Circle Demo")
fill edcirc le(gc, ql)
-l
-2
-3
-4
0
•
-7
ql=P oint( 8, 8)
q2=P oint( S, 5)
gc=Canvas("L ine Segment between 2 poi nts ")
line 2poin ts(g c,ql, q2)
► 0
-I
-1
-)
-1
':'-_"'.;'7--4
...... ➔---:
--:-"": l--
_l:--,-l:--,O---:l-l-
_3---:
_.---: , - S - ,- 1-
1
1. Line : A straight one dimensional figure having no thickness and extending infinitely in both
the directions.
2. Ray : A straight one dimensional figure having no thickness, begining at a point and
extending ilnfinitely in one direction.
3. Line Segment : A straight one dimensional figure begining at a point and ending at a point.
5. Half Plane : A Planer reigon consisting of all points on one side of an infinite straight line
and no points on the other side.
( a) Closed Half Plane : a half plane that includes points on that line.
(b) Open Half Plane: a half plane that does not include points on that line.
6. General position of llnes: a set of lines is said to be in a general position if no three of them
are concurrent (intersect at the same point).
For most of the algorithms, the direction of the rays or line segment is important.
The following code demonstrates how to travel from a point to another point with the direction
parallel to X and Y-a.xes.
def LineSegments():
ql = Point (1, 1)
q2 = Point(4,4)
gc = Canvas("Geometry of line segments", pl=Point(&,&), q2=Point(7,6))
filledcirc l e(gc, ql)
filledcircl e(gc, q2)
line2points(cgc ,pl ,Point(q2 .x, ql. y), color="red")
line2points(cgc,p2,Point(q2.x, ql.y), color="red")
gc.show()
Line Segments()
► J
0 i -- - - -~ --.....----~-----,...------,----'
0 6
X
• returning the sine and cosine of the angle between the points p I and p2
ge IT
Python Prog ramming Langua
)
S. Y.B.Sc.(Computer Science
de f qS in( ql, q2 ):
dis tan ce( ql, q2)
ret un i (q2 .y - ql . y) /
de f qC os( ql, q2 ):
dis tan ce (ql , q2)
ret un i (q2 .x - ql . x) /
de f ex ten d(q l,q 2,l ):
ql .x
x = 1 * qC os( ql, q2) +
l * qS in( ql, q2) + ql .y
y =
ret un i [ql , Po int (x, y)]
line
the task of constructing the
oin ts( ) function which has
Now we will use the lin e2p .
the ray and the line in general
segment to further constru ct
wargs):
de f ray (gc , ql, q2, **k
if ql != q2:
end (ql , q2, 188 8)
po sln fl, po sln f2 = ext
fl, pos lnf 2, **kwargs)
lin e2p oin ts( gc, po sln
from
nts ( I, I) and (3, 3) starting
w a ray passing through the poi
Now suppose we want to dra
the point (I, I).
NAL GEOMETRY
CHAPTER 2. COMPUTATIO
34
[I] Notes "t • 48 ~ f ij9+
Geometry ol r.,y
► l
Similarly, we can construct an infnite line which extends in both the directions. Refer the code
below;
Now suppose we want to construct a line segment passing through points (2, 2) and (4, 4).
ql=Point(2,2)
q2=Point(4,4)
gc = Canvas("Geometry of line segments", ql=Point(8,8), q2=Point(7,6))
line (gc , ql, q2)
35
CHAPTER2. COMPl!rATIONALGEOMEJRy
Python Programming Language n
S.Y.B.S c.(Computcr Science)
Geome uyolhn e
2.3 Polygons
ons:
Consider some basic definitions related with the polyg
or line segments meet.
I. Vertex: The point where two or more lines, rays
nce of points caJled vertices such that the
2. Polygonal chain : A curve speci fied by a seque
curve connects consecutive vertexes.
e first and last vertex are not con-
(a) Open Polygonal chain : A polygonal chain whos
nected.
(b) Closed Polygonal cbain : A polygonal chain
whose first and last vertex are connected.
where n ~ 3
Note that a polygonal chain bas vertexes v,, vz, ... , v,,
4. Convex set : A set of points q 1, qz, ... , qn such that all the edges (q;, qf) for i, j :S n and
i -:;:. j lie in the set
5. Polygon : The rcigon bounded by closed curve. A polygon is closed planar polygonal chain.
6. Simple polygon : The reigon bounded by a simple(non-intersecting) closed curve.
2.3.1 Triangle
As mentioned earlier the triangle is a 3 sided convex polygon. Refer the code below;
Now suppose we want to plot a triangle with vertices ( 1, 1), (4, 1) and ( 4, 4). Then refer the
code below;
LI
A(T) = ~ [::
Cx
: ::
Cy
!
1
] •
import nwnpy as np
def triangl eArea (a, b, c):
determinant=np .linalg .det( [[a.x, a.y, 1],
[b .x, b.y, 1], [c.x, c.y, 1]])
return &.S*determinant
Now suppose we wish to calculate the area of a triangle with vertices at ( l , I), (1,
5) and
(4, 1). Refer the code below:
a = Point( l,1)
b = Point( l, S)
c = Point( 4,l)
area= triangl eArea( a, b, c)
area
- S.999999999999997
Note that the above area is negative as the points are oriented in an anticlockwise sense.
(a) If the area of the triangle (a, b. c) > 0, then the point c is to the left of the Line Las
you travel from a to h. Otherwise it is to the right.
(b) lf the area of the triangle (a. b, c) ~ 0 then the point c is to the left of the line Lor
collinear with it.
(c) lf the area of the triangle (a. b , c) = 0 the point c is collinear with Line L
def RigbtOn(a, b, c) :
return Left (a, b, c)
de f Between(a, b, c):
if no t isC oll ine ar( a, b, c):
ret urn Fa lse
or (b. x <= c.x <= a.x )) and
ret urn ((a .x <= c.x <= b.x )
y <= c.y <= a.y ))
((a .y <= c . y <= b.y ) or (b.
ctly lie wit h res pec t to the
ver ify usi ng the abo ve fun ctio ns wh ere does the poi nt exa
On e can
to the abo ve con diti ons .
sid e of a tria ngl e wit h res pec t
and reflection
2.4 1\vo dimensionaJ rotation
giv en as follows:
I ) The two dim ens ion al rota
tion ma trix wit h an ang le (J is
L GEOMETRY
4-0 CHAPTER 2. COMPlJJ'ATIONA
S.Y.B.Sc.(Computer Science) Python Programming Language TI
refy = [ ~I ~] .
refyx = f~ ~].
• The reflection about the line y = -xis given by
Refer the python code below to construct the two dimensional rotation matrix using numpy,
import numpy as np
import math
def rotation(xy, theta):
X, y = xy
radians=matb.radians(theta)
c, s = np.cos(radians), np.sin(radians)
j = np.matrix([[c, s], [-s, c]])
m = np.dot(j, [x, y])
return float(m.T[&J), float(m.T[l])
The rotation matrix defined above is used to rotate the point (I, 0) through an angle of 90
degrees in the anticlockwise sense.
tbeta=-9&
point = (1, 19)
rotation(point,theta)
41 CHAPTER 2. COMPUTATIONALGEOMETRY
S.Y.B.Sc.(Computer Science) Python Programming Language II
(6 . 123233995736766e-17, 1.&)
Similarly a reflection through the X-axis can be coded as follows:
import numpy as np
import math
def refx(xy):
x, y = xy
j = np.matrix([[l, &], [&, -1]])
m = np.dot(j, [x, y])
return float(m.T[&]), float(m.T[l])
The reflection matrix defined above is used to re.fleet the point (O, 1) through the X-axis;
point= (t, 1)
refx(point)
The output is as follows;
($.$, -1.&)
I. The rotation matrix in three dimensions is considered along a particular axis (or equivalently
in a corresponding plane) as follows;
• Rotation along the Z-axis (or equivalently rotation in the XY-plaue in anticlockwise
sense) is given by the matrix,
cos 0 sin0 Ol
Rotz = -s~n0
[ ~e ~.
• Rotation along the Y-axis (or equivalently rotation in the XZ-plane in anticlockwise
sense) is given by the matrix,
cos O O - sin Ol
Roty = 0 1 0 .
[ sinO O cosO
• Rotation along the X-axis (or equivalently rotation in the YZ-plane in anticlockwise
l
sense) is given by the matrix,
Rotx;::: 0
] cosO
osinO .
o
[0 -sinO cosO
2. As io the case of Rotation, reflection too is performed along a selected ax.is (or equivalently
reflections relative to a particular plane). We mention the matrices as the reflection relative
to a particular plane,
• The reflection relative to the XY-planc (or equivalently reflection through the z-axis)is
given by,
I
I O O l
Refz = O 1 O .
0 0 -]
• The reflection relative to the XZ-plane (or equivalently reflection through the Y-axis)
is given by,
1
Refz = 0 -I O .
o ol
1
0 0 I
• The reflection relative to the YZ-plane (or equivalently reflection through the X-axis)
is given by,
Refz = 0
-1 oI Ool .
[ 0 0 1
Refer the following code where define a rotation of a point about the Z-ax.is;
57 ...Qf 69+
[I] Notes .. •
I
•••
0 i kopykitab.com/in + 0
[I] Notes ~ '°' 58 ~ f ij9+ >>
This comes from the fact that the weight of the sum is equal to one,
• they can be easily used to model geometric objects like parametric curves, mangles.
• they can can be computed in an efficient and numerically stable way via de Casteljau's
algorithm.
• can utilize convex optimization techniques for many algorithms (such as curve-curve inter-
section), since curves (and triangles etc.) are convex combinations of the basis.
• lhey ald physical analysis using finite element methods (FEM) on isogeometric models by
using geometric shape functions called NURBS to represent data.
• they are used in robust control of dynamic systems; utilizes convexity to create a hull of
curves.
The bezier package in python will help us compute and visualise the bezier curve with a given
number of control points
Suppose we wish to construct a Bezier curve of degree 3 and with the 4 polygonal vertices
(I, 1), (2, 3), (4, 3) and (6, 4).
import numpy as np
import bezier
nodes2 = np.asfortranarray(( [l,2,4,6),(1 ,3,3,4)])
curve2 = bezier.Curve.fro11LJ1odes(nodes2)
curve2
The output is as follows
The bezier curve can also be visualised using seaborn package as follows;
45
CHAPTER 2. COMPUTATIONAL GEOME"raY
[I] Notes ~ ~ 59 ~ f 69+ >>
35
30
25
20
IS
10
3 6
2
'
Fig. 2.8 : Bezier Curve
import seaborn
seaborn . set 0
ax = curve2 .plot(nUDL.pts=5)
The intersection points of the two bezier curves can also be determined. Refer the code below;
06
05
04
0.3
02
01
00
06 08 10
00 02 04
2. 7 Sel f Exercises
two
Com pute the Eucl idea n dista nce betw een the
1. Consider two points ( I 0, 8) and ( I, 15) .
points.
ram
non- identical poin ts. Also writ e a Pyth on Prog
2. Create a Python PointList consisting of 5
ecutive poin ts in this list.
to find the Euclidean distance between the cons
Con vert
where the values are fl oatin g poin t valu es.
3. Create a Python PointList with 10 poin ts
thi s list to a integ er point list.
find
any general position on a 12 x 12 grid . AJso
4 . Generate a rand om set of IO poin ts not in
the extreme points along the X and Y axis.
Notes ~ ~ 6 1 ~ f 69+
10. Draw a triangle with vertices at (2, 2), (2, 5) and (8, 2). AJso write down a Python program
to see if the point (3, 3) lies in the interior or exterior of the given triangle.
11. Draw a triangle with vertices ( I, I), (6, I) and ( I, 5). Write a Python program to see if the
triangle with these vertices is right angled.
12. Write a Python Program to rotate the point (2, 2) by an angle of 45 degrees in the clockwise
sense.
13. Write a Python Program to reflect the point (2, 2) through the X and the Y-axes respectively.
14. Write a Python program to rotate the point ( I, 2, 3) in the YZ-plane by an angle of 60
degrees.
15. Write a Python program to rotate the point ( 1,2,3) about the X-axis by an angle of 45
degrees.
16. Write a Python program to reflect the point (1, 2, 3) through the XY-planc.
17. Plot the Bczier curve with 4 control points ( l, 0), (3, 3), (6, 3) and (8, 1).
JS. Plot the Bezier curve with 3 control points ( l , 5), (3, I) and (7, 8)
19. Plot the Bezier curve with 6 control points {l , 2), (4, O), (8, 3), (5,4), (3, 3) and (6, 8)
20. Generate 5 random points on a 12 x 12 grid and connect them by line segments. Identify
whether they form a closed polygon.
ODD
CHAYTER2. COMPUTATIONALGEOMETRY
48
0 a kopykitab.com/in + m •••
62 ~ f 6 9 +
>>
N ot es ~ ~
[I]
Chapter 3
p e r a ti o n s Research in Python
S tu d y o f O
in Python
3.1 Linear Programming ue
obtain an op tim al val
op tim iza tion is a ma thematical method to ca se of a
Ll ne ar pro gra mm ing
or Li ne ar um value in
mi zal.io n pro ble m or finding the minim ble ms the
ca se of nuu:i onships. lnc ase of rea
l life pro
(max im um va lue in su bjected to lin ea r relal.i
ble m) wh ich are
minimization pro ho ld true.
nts are als o ass um ed to
no n-n ega tiv ity constrai o specific typ e of pro ble
ms which include,
on e de als wi th tw
M or e generally, tained by solvin g
de als wi th ma xim izi ng the profit to be ob
m usually
• Ma xim iza tio n pro ble
the pro ble m. ction while
wi th mi oimi7. ing the total co st of produ
m usu ally de als
• Minim12atlon pro ble
solving the proble m.
• 63 ~ f 1S9+
>>
[1J Notes •
e JI
Python Programming Languag
S. Y.B.Sc.(Compuler Science)
mu st satisfy
3. Constraints that the solution ents .
diet ary requ irem
daily amo unt of mix and the
The constra ints repr esen t the
700 lb of feed eac h day
The catt le farm requires atle ast
x +y ~ 700 .
o.21x - o.3y ~o
0.03x - 0.0ly ~0
X, y :2:0.
The Python Library PuLP provides methods to solve such kind of problems. Refer the
following code to solve such a problem us ing this library.
The above code will display the L.P.P. ln order to solve the L .P.P. we wiU use the Lp_prob. solve()
function defined in PuLP.
status= Lp_prob.solve()
print(p.LpStatus[status])
print(p.value(x), p.value(y),p . value(Lp_prob.objective))
This gives the value of x =411. 76471, y =288.23529 and the minimum value of
Z = 312.94117400000005.
• c = (c,, c2, .... , c,.) are the coeffecients in the objective function.
• x = (x 1, x2, ... , x,.) are the variables of the problem.
• A is a m x II matrix of coeffecieots
• b = (b 1, b2, ..., bm) is a vector of non-negative constants.
Problem 2: Consider a production house producing 4 items. Note that the daily items
produced produced for the four items are given by x , y, z, w respectively. The goal is to dally
production so as to yield maximum profit considering the following constraints;
• The profit per unit of the item is t20, t 12. t40 and '25, respectively.
• The total number of items produced per day cannot exceed 50.
• The items require the consumption of two types of raw material namely A and B and
their consumption per unit of item which is given in the table below;
Raw Material item 1 item 2 item3 item4
A 3 2 1 0
B 0 1 2 3
• Due to costing with the logistics the production house can consume up to 100 units of
raw material A and 90 units of raw material B.
x+y+z+w ;s; 50
3x + 2y + z ;s; 100
y +2z +3w :s: 90
x, y, z, w 2: 0.
To solve this problem using a simplex method, we will use the linprog () function defined
in the scipy.optimize module. Note the function linprog() solves only minimization
problems. Incase of problem of Maximization type,convert the problem in to minimization
type as shown below;
Also note that while solving the problem using Jinprog functions three methods are avaliable.
(a) method="interior point" which selects the interior point method.This is set as a default
option.
(b) method="revised simplex" which selects the revised twp phase simplex method.
(c) method="simplex" selects the primitive simplex method.
Hence, the values of the quantities are x = 5, y = 0, z = 45, w = 0 and the maximum profit
obtained in such a case is 1900.
In addition, these are some other conclusions that one can draw;
• The third item brings the largest profit per unit so that the production house will produce
it on a large scale.
• The first slack variable is O which means that the first constraint mentioned turns out
to be an equality. It means that the production house produces 50 units of all the items
per day which is to its full capcity.
• The second slack variable is 40 which means that the production house consumes 60
units of the raw material A out of the avaliable 100 units.
• The third slack variable is Owhich means that the production house consumes all of
the 90 units of the raw material B. The entire raw material is consumed for the third
item because of which the second and fourth item cannot be manufactured as well as
the third item cannot be manufactured by a quantity more than 45. There is a deficit of
the raw material B.
I II m
M I 2 1
N 2 l 1.25
A B C
p 160 100 150
Q 100 120 100
subjec t to,
2x1 + xi$ 10
x, + 2x2 - 2x3 5 20
x2 + 2x3 5 5
x1,x2 ,x3 ~ 0