You are on page 1of 63

Go, change the world

RV College of
Engineering
Dept of Mech. Engg. Python for Mechanical Engineers
RV College of Go, change the world
Engineering
Course Content
 Introduction to Plotting and Visualization,
 Matplot functions,
 Seaborn
 Solving Dynamic Equations,
 Curve Fitting and Regression,
 Understanding Iterative Solvers,
 Data Analysis,
 Programs on simple equation of Mechanics,
 Mechanical vibration, thermal, heat transfer and fluid mechanics
RV College of Go, change the world
Engineering Data Visualisation
 Data visualization is a way to represent information graphically, highlighting patterns and
trends in data and helping the reader to achieve quick insights.
 Data visualization is the graphical representation of different pieces of information or
data, using visual elements such as charts, graphs, or maps.

 Python provides various libraries that come with different features for visualizing data. All
these libraries come with different features and can support various types of graphs. In this
tutorial, we will be discussing four such libraries.
 Matplotlib
 Seaborn
 Bokeh
 Plotly
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
E.g. Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt xpoints = np.array([0,1,2,3,4,5,6])


import numpy as np ypoints = np.array([0,10,20,30,70,80, 250])

xpoints = np.array([0, 6]) plt.plot(xpoints, ypoints)


ypoints = np.array([0, 250]) plt.show()

plt.plot(xpoints, ypoints)
plt.show() plt.plot(xpoints, ypoints, 'o')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Plotting x and y points
 The plot() function is used to draw points (markers) in a diagram.
 By default, the plot() function draws a line from point to point.
 The function takes parameters for specifying points in the diagram.
 Parameter 1 is an array containing the points on the x-axis.
 Parameter 2 is an array containing the points on the y-axis.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers Shape
You can use the keyword argument marker to emphasize each point with a specified marker:
Marker Description
'o' Circle 'p' Pentagon plt.plot(ypoints, 'o:r')
'*' Star 'H' Hexagon plt.show()
'.' Point 'h' Hexagon
',' Pixel 'v' Triangle Down
'x' X '^' Triangle Up
'X' X (filled) '<' Triangle Left
'+' Plus '>' Triangle Right
'P' Plus (filled) '1' Tri Down
's' Square '2' Tri Up
'D' Diamond '3' Tri Left
'd' Diamond (thin) '4' Tri Right
'_' Hline '|' Vline
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
 Format Strings fmt
 You can use also use the shortcut string notation parameter to specify the marker.
Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line

plt.plot(ypoints, 'X--g')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:

Color Syntax Description


'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

plt.plot(ypoints, 'X-.b')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:

Color Syntax Description


'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

plt.plot(ypoints, 'om--')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:

plt.plot(ypoints, marker ='o', ms=5)


plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Marker Color
You can use the keyword argument markeredgecolor or the shorter mec to set the color of the edge of
the markers:

plt.plot(ypoints, marker ='o', ms=5, mec='r')


plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Line
Linestyle: You can use the keyword argument linestyle, or shorter ls, to change the style of the
plotted line:

plt.plot(ypoints, linestyle = 'dotted')


plt.show()

plt.plot(ypoints, linestyle = 'dashed')


plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Line Width
You can use the keyword argument linewidth or the shorter lw to change the
width of the line.

plt.plot(ypoints, linewidth = 10)


plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Multiple Lines
You can plot as many lines as you like by simply adding more plt.plot() functions:

# Multiple lines
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
forged1= np.array([23,21,20,27])
forged2 = np.array([20,18,17,16])
forged3=np.array([19,17,16,21])

plt.plot(xpoints, ascast)
plt.plot(xpoints, forged1)
plt.plot(xpoints, forged2)
plt.plot(xpoints, forged3)

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for
the x- and y-axis.

plt.xlabel("Average Pulse") plt.xlabel("Average Pulse")


plt.ylabel("Calorie Burnage") plt.ylabel("Calorie Burnage")
plt.show() plt.plot(xpoints, ascast)
plt.plot(xpoints, forged1)
plt.plot(xpoints, forged2)
plt.plot(xpoints, forged3)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib

Create a Title for a Plot


With Pyplot, you can use the title() function to set a title for the plot.

plt.title("Sports Watch Data")


plt.show()

plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.title("Computer")
plt.plot(xpoints, ascast)
plt.plot(xpoints, forged1)
plt.plot(xpoints, forged2)
plt.plot(xpoints, forged3)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Set Font Properties for Title and Labels
You can use the fontdict parameter in xlabel(), ylabel(), and title() to set
font properties for the title and labels.

font1 = {'family':'serif', 'color':'blue', 'size':20}


font2 = {'family':'serif', 'color':'darkred', 'size':10}
plt.title("Computer Science", fontdict=font1)
plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Position the Title
You can use the loc parameter in title() to position the title. Legal values are:
'left', 'right', and 'center'. Default value is 'center'

plt.title("Computer Science", fontdict=font1, loc='right')


plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.show()
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Add Grid Lines to a Plot
With Pyplot, you can use the grid() function to add grid lines to the plot

plt.title("Computer Science", fontdict=font1,


loc='center')
plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.grid()
. plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Specify Which Grid Lines to Display
You can use the axis parameter in the grid() function to specify which grid lines to display.
Legal values are: 'x', 'y', and 'both'. Default value is 'both'.
plt.title("Computer Science", fontdict=font1, loc='center')
plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.grid(axis='x')
plt.show()
. plt.title("Computer Science", fontdict=font1, loc='center')
plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.grid(axis='y')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Set Line Properties for the Grid

plt.title("Computer Science", fontdict=font1,


loc='center')
plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)
plt.grid(color ='green', linestyle='--', linewidth=0.5)
plt.show()

.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Display Multiple Plots
With the subplot() function you can draw multiple plots in one figure:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
plt.subplot (2,1,1)
plt.plot(xpoints, ascast)
.
xpoints = np.array([0,2,4,6])
forged1= np.array([23,21,20,27])
plt.subplot(2,1,2)
plt.plot(xpoints, forged1)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Draw more than three plots: :
xpoints = np.array([0,2,4,6])
ascast = np.array([27,25,24,25])
forged1= np.array([23,21,20,27])
forged2 = np.array([20,18,17,16])
forged3=np.array([19,17,16,21])

import matplotlib.pyplot as plt


import numpy as np
plt.subplot (2,3,1)
. plt.plot(xpoints, ascast)
plt.subplot (2,3,2)
plt.plot(xpoints, forged1)
plt.subplot (2,3,3)
plt.plot(xpoints, forged2)
plt.subplot (2,3,4)
plt.plot(xpoints, forged2)
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Title:
import matplotlib.pyplot as plt
import numpy as np

plt.subplot (2,3,1)
plt.plot(xpoints, ascast)
plt.title('AsCast ')

plt.subplot (2,3,2)
plt.plot(xpoints, forged1)
plt.title('Forged-1')

. plt.subplot (2,3,3)
plt.plot(xpoints, forged2)
plt.title('Forged-2')
plt.subplot (2,3,4)
plt.plot(xpoints, forged2)
plt.title('Forged-3')

Super Title; You can add a title to the entire figure with the suptitle() function:
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Super Title; You can add a title to the entire figure with the suptitle() function:

plt.subplot (2,3,3)
plt.plot(xpoints, forged2)
plt.title('Forged-2')
plt.subplot (2,3,4)
plt.plot(xpoints, forged2)
plt.title('Forged-3')
plt.suptitle("Experimental Results")
.
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Scatter: With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the same length, one
for the values of the x-axis, and one for values on the y-axis:

import matplotlib.pyplot as plt


import numpy as np
ascast = np.array([1,2,3,4,5,5,6,7,8,9,10])
forged1= np.array([23,25,45,56,7,8,9,10,19,22,23])
plt.scatter(ascast, forged1)
plt.show()
.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Compare Plots

import matplotlib.pyplot as plt


import numpy as np
ascast = np.array([1,2,3,4,5,5,6,7,8,9,10])
forged1= np.array([23,25,45,56,7,8,9,10,19,22,23])
forged2 =
np.array([100,120,123,230,125,134,134,123,156,134,134])
plt.scatter(ascast, forged1)
plt.scatter (ascast, forged2)
.
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Colors
You can set your own color for each scatter plot with the color or the c argument:

plt.scatter(ascast, forged1, color ='hotpink')


plt.scatter (ascast, forged2, color ='blue')
plt.show()

.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for
the c argument:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors =
.np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray",
"cyan","magenta"])

plt.scatter(x, y, c=colors)

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
ColorMap
 The Matplotlib module has a number of available colormaps.
 A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.
 Here is an example of a colormap:
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
. colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.colorbar()

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Size
You can change the size of the dots with the s argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
. sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes)

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Alpha
You can adjust the transparency of the dots with the alpha argument.
Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
.
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes, alpha=0.7)

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Combine Color Size and Alpha
You can combine a colormap with different sizes on the dots. This is best visualized if the dots are
transparent:
import matplotlib.pyplot as plt
import numpy as np

x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
. sizes = 10 * np.random.randint(100, size=(100))

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')

plt.colorbar()

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Bars
Creating Bars: With Pyplot, you can use the bar() function to draw bar graphs
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh() function

import matplotlib.pyplot as plt


import numpy as np
import matplotlib.pyplot as plt
x = np.array(["A", "B", "C", "D"]) import numpy as np
y = np.array([3, 8, 1, 10])
. x = np.array(["A", "B", "C", "D"])
plt.bar(x,y) y = np.array([3, 8, 1, 10])
plt.show()
plt.barh(x, y)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Bar Color
The bar() and barh() takes the keyword argument color to set the color of the bars:

plt.barh(x, y, color='red')
plt.show()

.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Bar Width
The bar() takes the keyword argument width to set the width of the bars:

plt.bar(x, y, width=0.5)
plt.show()

Bar Height
The bar() takes the keyword argument width to set the width of the bars:
.
plt.barh(x, y, height=0.5)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib
Matplotlib Histograms Histogram
 A histogram is a graph showing frequency distributions.
 It is a graph showing the number of observations within each given interval.

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
.n, bins, patches = plt.hist(x, num_bins, facecolor='red', alpha=0.75)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 20
# the histogram of the data
.
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib

import matplotlib.pyplot as plt


import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show()

.
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib-PieChart
mport matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels =mylabels, startangle = 90)


plt.show()

.
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels =mylabels,explode = myexplode)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Matplotlib-PieChart
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]
plt.pie(y, labels =mylabels, colors =mycolors)
plt.show()

import matplotlib.pyplot as plt


import
. numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels =mylabels,explode = myexplode, colors =mycolors)
plt.legend()
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Seaborn is a library that uses Matplotlib underneath to plot graphs. It will be used to
visualize random distributions.
Distplots : Distplot stands for distribution plot, it takes as input an array and plots a
curve corresponding to the distribution of points in the array.

import matplotlib.pyplot as plt


import seaborn as sns
sns.distplot([0, 1, 2, 3, 4, 5])
. plt.show()

import matplotlib.pyplot as plt


import seaborn as sns
sns.distplot([0, 1, 2, 3, 4, 5], hist=False)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Load a dataset with Seaborn
Seaborn has a variety of built-in datasets that you can load like this:
.
import seaborn as sns
df = sns.load_dataset('iris')
df.head()

.
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a scatter plot
Scatter plots are useful to show relationships between numeric
variables.
import
. seaborn as sns
import matplotlib.pyplot as plt

age = [10,12,15,16,17,17,20,25,30,35,37,39,40,42,45,50]
height = [120,130,145,143,182,186,170,172,172,182,178,168,182,187,160,166]

.sns.scatterplot(x=age, y=height)
plt.xlabel('age')
plt.ylabel('height')
plt.title('Height vs age')
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a Count plot
Count plots are useful to show relationships between categorical
variables.
import seaborn as sns
import matplotlib.pyplot as plt

colors = ['Blue','Blue','Red','Red','Red','Yellow','Yellow','Yellow','Yellow','Yellow']

sns.countplot(x=colors)
.plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Use Seaborn with Pandas
You can use seaborn with Pandas dataframes quite easily using the data

import matplotlib.pyplot as plt


import pandas as pd
import seaborn as sns

df = pd.read_csv('C:\\Users\\KRISHNA M\\Desktop\\kri1.csv')
print (df)
.sns.countplot(x='Duration', data=df)
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Add a Third Variable with Hue
You can add more than two variables to a seaborn visualization by
using the hue keyword
import seaborn as sns

data = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length',
y='sepal_width',
data=data,
. hue='species')
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Create a lineplot with Seaborn
Often, you will need to work with dates. One of the most useful
data visualizations for dates is the line plot.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = sns.load_dataset('flights')
print (df)
. f_1960 = df[df['year'] == 1960]
sns.relplot(x='month',y='passengers',
data=f_1960,
kind='line')

plt.xticks(rotation=90)
plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Boxplots are useful to show the distribution of quantitative data
across categorical variables.
Understand the boxplot.
 box: 25th to 75th percentile
 middle line: median
 whiskers: spread of distribution.
 points: outliers
import matplotlib.pyplot as plt
import seaborn as sns
.
tips = sns.load_dataset('tips')

g = sns.catplot(x='sex', y='tip',
data=tips,
kind='box')

plt.show()
RV College of Go, change the world
Engineering Data Visualisation-Seaborn
Displot
Let’s recreate our normal distribution graph, this time using Seaborn distplot.

import numpy as np
normal_matrix =np.random.rand(100,1000)
matrix_sum = np.sum(normal_matrix,0)
sns.distplot(matrix_sum, kde=True)

.
RV College of Go, change the world
Engineering Data Visualisation-Seaborn

Create a Pairplot in Seaborn


Pairplots are a fantastic way to visualize your multiple subplots at
once to analyse all your variables.
.
import seaborn as sns
df = sns.load_dataset('iris')
print (df)
sns.pairplot(df, hue="species", height=2)
.
RV College of Go, change the world
Engineering Solving Dynamic Equations-First Order
First Order System Simulation
Consider a first order differential equation with constants Kp=3 and rp=2, input u, and output
response y.
𝑑𝑦 # Transfer function Method
𝑟𝑝 𝑑𝑡 = −𝑦 + 𝑘𝑝 𝑈 import numpy as np
Laplace Trnafer from scipy import signal
Rps = - Y(s) + kp U(s) import matplotlib.pyplot as plt
from scipy.integrate import odeint
𝑌(𝑠) 𝐾𝑝
= Kp = 3.0
𝑈(𝑠) 𝑟𝑝 𝑠+1
tau = 2.0
num = [Kp]
den = [tau,1]
sys=signal.TransferFunction(num,den)
t1,y1 = signal.step(sys)
plt.figure(1)
plt.plot(t1,y1,'r-')
plt.show()
RV College of Go, change the world
Engineering Solving Dynamic Equations-First order
# Differencial Method
def model(y,t):
u=1
return (-y + Kp * u)/tau
t2 = np.linspace(0,14,100)
y2 = odeint(model,0,t2)
plt.plot(t2,y2,'b--')
plt.show()
# Comparision between LT and conventional system
plt.plot(t1,y1,'r-', linewidth=3, label = 'Transfer Function')
plt.plot(t2,y2,'b--', linewidth =3, label ='ODE Intigrator')
plt.xlabel('Time')
plt.ylabel('Response (y)')
plt.legend(loc='best')
plt.show()
RV College of Go, change the world
Engineering Solving Dynamic Equations-Second order
# Transfer function Method
Second Order System Simulation import numpy as np
from scipy import signal
𝑑 𝑦 2
𝑑𝑦 import matplotlib.pyplot as plt
2 = 2 +2 + 𝑦 = 𝐾𝑝 𝑢 (𝑡 − ) from scipy.integrate import odeint
𝑑𝑡 𝑑𝑡 Kp = 2.0 # gain
tau = 1.0 # time constant
Laplace transform zeta = 0.1 # damping factor
2 = s2 + 2   s + Y[s] = KpU(S) e-S theta = 0.0 # no time delay
du = 1.0 # change in u
𝑒 −𝑠
𝑌(𝑠) 𝐾𝑝 num = [Kp]
=
𝑈(𝑠) 2𝑠2+2  𝑠+1 den = [tau**2,2*zeta*tau,1]
sys1 = signal.TransferFunction(num,den)
t1,y1 = signal.step(sys1)
Kp = 2.0 gain plt.figure(1)
 = 1.0 time constant plt.plot(t1,y1*du,'b--',linewidth=3,label='Transfer Fcn')
plt.legend(loc='best')
 = 0.25 damping factor
plt.xlabel('Time')
 = 0.0 no time delay plt.ylabel('Response (y)')
plt.show()
RV College of Go, change the world
Engineering Solving Dynamic Equations-Second order
# 2 ODE Integrator
def model(x,t):
y = x[0]
dydt = x[1]
dy2dt2 = (-2.0*zeta*tau*dydt - y + Kp*du)/tau**2
return [dydt,dy2dt2]
t2 = np.linspace(0,50,100)
x2 = odeint(model,[0,0],t2)
y2 = x2[:,0] # compression
plt.plot(t2,y2,'r-',linewidth=1,label='ODE Integrator') plt.plot(t1,y1*du,'b--',linewidth=3,label='Transfer Fcn
plt.xlabel('Time') plt.plot(t2,y2,'r-',linewidth=1,label='ODE Integrator')
plt.ylabel('Response (y)') plt.legend(loc='best')
plt.legend(loc='best') plt.xlabel('Time')
plt.show() plt.ylabel('Response (y)')
plt.show()
RV College of
Engineering Curve fitting Go, change the world

Curve fitting is a type of optimization that finds an optimal set of parameters for a defined
function that best fits a given set of observations.

A straight line between inputs and outputs can be defined as follows:

Single Input

Y = aX + b where X is input and Y is out put


a & b are constants

Two input
a line mapping function for two input variables may look as follows:
. Z = aX +bY +C where X and Y inputs, Z is out put and a,b& c are constants

.
RV College of
Engineering Curve fitting Go, change the world

A squared version of the input # load input variables from input


weighted by another parameter: import matplotlib.pyplot as plt
import numpy as np
Y = aX + b X2 +c X is input, Y is import scipy as sc
output and a,b & c are chantant x_values = np.array([1,2,3,4,5,6,7,6,9,10])
y_values = np.array([10,22,28,29,32,37,47,57,69,80])
In other form of curve fitting def objective(x, a, b, c):
return a * x + b
Y = a log (x) + b popt, _ = sc.optimize.curve_fit(objective, x_values, y_values)
Y = a e-bx+c a,b,c = popt
Y = a sin bx + c y_new = objective(x_values, a, b, c)
plt.plot(x_values, y_values, '*')
. plt.plot (x_values, y_new)
plt.xlabel('x-axis')
. plt.ylabel('Y-axis')
plt.show()
RV College of
Engineering Curve fitting Go, change the world

import matplotlib.pyplot as plt


import pandas as pd
import numpy as np
import scipy as sc
dataframe = pd.read_csv('C:\\Users\\KRISHNA M\\Desktop\\longley.csv', header = None)
data =dataframe.values
x, y = data[:, 0], data[:, -1]
def map(x, a, b):
return a * x + b
popt, _ = sc.optimize.curve_fit(map, x, y)
a, b = popt
print ('Curve fitting equaiton y= {0}x+{1}'.format(a,b))
y_new = map(x, a, b)
. plt.scatter (x,y)
plt.plot(x,y_new)
.
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
RV College of
Engineering
Curve fitting Go, change the world

import matplotlib.pyplot as plt


import pandas as pd
import numpy as np
import scipy as sc
dataframe = pd.read_csv('C:\\Users\\KRISHNA M\\Desktop\\longley.csv', header = None)
data =dataframe.values
x, y = data[:, 4], data[:, -1]
def map(x, a, b, c):
return a * x**2 + b*x+c

popt, _ = sc.optimize.curve_fit(map, x, y)
a, b, c = popt
print ('Curve fitting equaiton y= {0}x2+{1}x+{2}'.format(a,b,c))
y_new = map(x, a, b, c)
. plt.scatter (x,y)
plt.plot(x,y_new, '--', color='red')
. plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
RV College of
Engineering Curve fitting Go, change the world

import matplotlib.pyplot as plt


import pandas as pd
import numpy as np
import scipy as sc
dataframe = pd.read_csv('C:\\Users\\KRISHNA M\\Desktop\\longley.csv', header = None)
data =dataframe.values
x, y = data[:, 4], data[:, -1]
def map(x, a, b, c,d):
return a * x**3 + b*x**2+c*x+d
popt, _ = sc.optimize.curve_fit(map, x, y)
a, b, c, d = popt
print ('Curve fitting equaiton y= {0}x3+{1}x2+{2}x1+{3}'.format(b,a,c,d))
y_new = map(x, a, b, c,d)
plt.scatter (x,y)
.
plt.plot(x,y_new, '--', color='red')
plt.xlabel("x-axis")
. plt.ylabel("y-axis")
plt.show()
RV College of
Engineering Understanding Iterative Solvers Go, change the world

Solve the following system of linear equations using Iterative solver method, use a pre-defined
threshold 𝜖=0.01 Do remember to check if the converge condition is satisfied or not.

x1,x2,x3 = 0,0,0
epsilon =0.01
converge =False
x_old = np.array([x1, x2, x3])

print('Iteration results') if dx < epsilon:


print(' k, x1, x2, x3, dx') converged = True
for k in range(1, 50): print('Converged!')
x1 = (14-3*x2+3*x3)/8 break
x2 = (5+2*x1-5*x3)/(-8) x_old = x
x3 = (-8-3*x1-5*x2)/(-5) if not converged:
x = np.array([x1, x2, x3])
. print('Not converge, increase the # of iterations')
# check if it is smaller than threshold
dx = np.sqrt(np.dot(x-x_old,x-x_old))
. print("%d, %.4f, %.4f, %.4f, %.5f"%(k, x1, x2, x3, dx))
RV College of
Engineering Understanding Iterative Solvers Go, change the world

Using Sympy to Solve Trig and Exponential Equations

import sympy as sp
x = sp.Symbol('x')
y =sp.Symbol ('y')
p = x**2+x-6
eq = sp.Eq(p,0)
sol = sp.solve (eq, x)
print (sol)

.
RV College of
Engineering Data Analysis Go, change the world

Data Analytics Process Steps


There are primarily five steps involved in the data analytics process, which include:
1. Data Collection: The first step in data analytics is to collect or gather relevant data from
multiple sources. Data can come from different databases, web servers, log files, social
media, excel and CSV files, etc.
2. Data Preparation: The next step in the process is to prepare the data. It involves cleaning
the data to remove unwanted and redundant values, converting it into the right format, and
making it ready for analysis. It also requires data wrangling.
3. Data Exploration: After the data is ready, data exploration is done using various data
visualization techniques to find unseen trends from the data.
4. Data Modeling: The next step is to build your predictive models using machine learning
algorithms to make future predictions.
5. Result interpretation: The final step in any data analytics process is to derive meaningful
.
results and check if the output is in line with your expected results.
.

45+ Data Analysis Projects with Python | by Aman Kharwal | Medium

You might also like