Learn Python in Malayalam | Chapter 10 | Matrices in python | addition & multiplication | Transpose | inverse | rank of a matrix
Experiment No 7 : Simple Data Analysis with Spreadsheets
Objectives
Display an electrical signal and export it as a .csv file.
Read this .csv or .xls file as an array and plot it.
Compute the mean and standard deviation of the signal. Plot its histogram with an appropriate bin size.
Theory
Pandas is a powerful and flexible Python package that allows you to work with labeled and time series data. It also provides statistics methods, enables plotting, and more. One crucial feature of Pandas is its ability to write and read Excel, CSV, and many other types of files. Functions like the Pandas read_csv() method enable you to work with files effectively. You can use them to save the data and labels from Pandas objects to a file and load them later as Pandas Series or DataFrame instances. A comma-separated values (CSV) file is a plaintext file with a .csv extension that holds tabular data. This is one of the most popular file formats for storing large amounts of data. Each row of the CSV file represents a single table row. The values in the same row are by default separated with commas, but you could change the separator to a semicolon, tab, space, or some other character.
Steps to follow
First you have to create generate a sine signal values
Save that values to a variable dat
You can use this dat to create an instance of a Pandas DataFrame.
For that you need to import Pandas
You can reverse the rows and columns of a DataFrame with the property .T:
You can save your Pandas DataFrame as a CSV file with .to_csv():
Once your data is saved in a CSV file, you’ll likely want to load and use it from time to time. You can do that with the Pandas read_csv() function:
Use pandas .plot() function to plot the read data
Use .hist() to plot the histogram of the data
Use .std() function to find the standard deviation
Use .mean() function to find the mean
Program
#importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Get x values of the wave
t = np.linspace(0,1,100)
# calculating the amplitude
y = np.sin(2*np.pi*t) # calculating sine wave
dat = [t,y]
# writing the value in to data.csv
df = pd.DataFrame(data=dat,index=["Time","Amplitude"]).T
# df
df.to_csv('data.csv')
#Reading the file data.csv
df1=pd.read_csv('data.csv',index_col=0)
# df1
#Plotting the function from read value
df1.plot(x="Time",y="Amplitude")
plt.show()
# Creating histogram
df1.hist(column="Amplitude")
# Show plot
plt.show()
# Standard deviation of the value
print("Standard Deviation")
print(df1.std(0))
# Mean of the values
print("Mean")
print(df1.mean(0))
Output
Standard Deviation
Time 0.293045
Amplitude 0.707107
dtype: float64
Mean
Time 5.000000e-01
Amplitude -1.604953e-17
dtype: float64
Inference
Generated an electrical signal and exported it as a .csv file.
Read that .csv file as an array and plotted it.
Computed the mean and standard deviation of the signal. Plotted its histogram with an appropriate bin size.
Experiment No 6 : Solution of Ordinary Differential Equations
Objectives
Solve the first order differential equation
dxdt+2x=0
with the initial condition x(0) = 1
Solve for the current transient through an RC network (with RC = 3) that is driven by
5 V DC
the signal 5e-tU(t)
and plot the solutions.
Solve the second order differential equation
dxdt2+2dxdt+2x = e-t
Solve the current transient through a series RLC circuit with R = 1, L = 1mH and C = 1 F that is driven by
5 V DC
the signal 5e-tU(t)
Theory
Solving first order differential equation
An example of using ODEINT is with the following differential equation with parameter the initial condition x(0) =5 and the following differential equation.
dxdt+2x=0
The Python code first imports the needed Numpy, Scipy, and Matplotlib packages. The model, initial conditions, and time points are defined as inputs to ODEINT to numerically calculate x
Programe
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dx/dt
def model(x,t):
k = 2
dxdt = -k * x
return dxdt
# initial condition
x0 = 5
# time points
t = np.linspace(0,20)
# solve ODE
x = odeint(model,x0,t)
# plot results
plt.plot(t,x,label="K=2")
plt.title("FIrst order Differential equation response")
plt.xlabel('time')
plt.ylabel('x')
plt.legend()
plt.show()
Output
An optional fourth input is args that allows additional information to be passed into the model function. The args input is a tuple sequence of values. The argument k is now an input to the model function by including an additional argument.
Programe
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dx/dt
def model(x,t,k):
dxdt = -k * x
return dxdt
# initial condition
x0 = 5
# time points
t = np.linspace(0,20)
# solve ODE
k=.1
x1 = odeint(model,x0,t,args=(k,))
k=.5
x2 = odeint(model,x0,t,args=(k,))
k=1
x3 = odeint(model,x0,t,args=(k,))
# plot results
plt.plot(t,x1,label="K=.1")
plt.plot(t,x2,label="K=.5")
plt.plot(t,x3,label="K=1")
plt.title("First order Differential equation response with diff K values")
plt.xlabel('time -->')
plt.ylabel('x-->')
plt.legend()
plt.show()
Output
Current transient through an RC network
An RC circuit is a circuit with both a resistor (R) and a capacitor (C). RC circuits are a frequent element in electronic devices. They also play an important role in the transmission of electrical signals in nerve cells.
A capacitor can store energy and a resistor placed in series with it will control the rate at which it charges or discharges. This produces a characteristic time dependence that turns out to be exponential. The crucial parameter that describes the time dependence is the "time constant" R C
Aside from the voltage source, the RC circuit is composed of a capacitor and a resistor, we therefore assume that self-inductance is negligible. When we close the circuit, there is no inductance here so the current will just jump to the V/R value and since the capacitor is charging up and building a voltage, we can expect the current at the resistor to drop as times goes by. The differential equation we have now is the following:
By solving it, one finds:
Therefore
The current through the resistor drops exponentially, depending on a time constant tau = 1/RC. This behaviour is indeed what we find by running the simulation in Python
Program
import numpy as np
import matplotlib.pyplot as plt
# plt.style.use('ggplot')
t = np.linspace(0,1,1000)
v= 5
r = 3000 #R Value
c = 100 * 10 ** (-6) #C value
q = c*v*(1-np.exp((-1/(r*c))*t))
i = (v/r)*np.exp((-1/(r*c))*t)
plt.plot([0,t[-1]],[c*v,c*v],label='Charge peak')
plt.plot(t,q,label='Charge of the capacitor (C)')
plt.plot(t,i,label='Current (A)')
print('Tau',1/(r*c))
print('Peak current (A)',v/r)
plt.xlabel('Time (s)')
plt.title('RC circuit')
plt.legend()
plt.show()
Output
Tau 3.3333333333333335
Peak current (A) 0.0016666666666666668
With the signal 5e^tU(t)
Program
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,1,1000)
v = 5 * np.exp(-1*t) #DC Voltage
r = 3000 #R Value
c = 100 * 10 ** (-6) #C value
q = c*v*(1-np.exp((-1/(r*c))*t))
i = (v/r)*np.exp((-1/(r*c))*t)
plt.plot([0,t[-1]],[c*np.average(v),c*np.average(v)],label='Charge peak')
plt.plot(t,q,label='Charge of the capacitor (C)')
plt.plot(t,i,label='Current (A)')
print('Tau',1/(r*c))
print('Peak current (A)',np.average(v)/r)
plt.xlabel('Time (s)')
plt.title('RC circuit')
plt.legend()
plt.show()
Output
Tau 3.3333333333333335
Peak current (A) 0.0010536207178662611
Solution of the second order differential equation
dxdt2+2dxdt+2x = e-t
Which give
Y’’ + 2y’ + 2y = e-t
We can turn this into two first-order equations by defining a new dependent variable.
Z == y’’ → z’ + 2z + y = e-t
With initial conditions z(0) = y(0) = 0
Program
# Import the required modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def dx_dt(X, t):
# Here X is a vector such that y=X[0] and z=X[1]. This function should return [y', z']
return [X[1], -2*X[1] - 1*X[0] + np.exp(-t)]
X0 = [0, 0]
t = np.linspace(0, 10, 200)
Xs = odeint(dU_dx, X0, t)
ys = Xs[:,0]
plt.xlabel("t")
plt.ylabel("y")
plt.title("second order diffrential equation response")
plt.plot(t,ys);
# print(Us)
# print(ys)
Output
Transient response of RLC circuit
A series RLC circuit , the figure show the typical RLC circuit and described by the following equation
The solution of Equation is
where Ï„ is a time constant determined by
In Equation, ω is the natural resonant frequency determined by:
Figure The transient voltage uc across capacitor for a RLC circuit
Program
#importing the library
import numpy as np
import matplotlib.pyplot as plt
L=1 # value of Inductor
R=1 # value of resistor
C=.001 #value of capacitor
tow=2*(L/R) #time constant
t = arange(0, 10, 0.01)
E1=5
E2=5*exp(-1*t)
w=sqrt((1/(L*C)-((R*R)/(4*(L*L))))) # resonant frequency
u_c1 = E1*exp(-1*(t)/tow)*cos(w*t) # response with E = 5V
u_c2 = E2*exp(-1*(t)/tow)*cos(w*t) # response with E =5E^(-t)U(t)
#Plotting the values
rcParams["figure.figsize"] = (7,10) # changing the figure size
fig, ax = plt.subplots(2)
ax[0].plot(t,u_c1)
ax[0].set_title("Transient response for E =5V")
ax[0].set_xlabel("t")
ax[0].set_ylabel("u_c")
ax[1].plot(t,u_c2)
ax[1].set_title("Transient response for E =5E^(-t)U(t)")
ax[1].set_xlabel("t")
ax[1].set_ylabel("u_c")
show()
Output
inference
Solved the first order differential equation
dxdt+2x=0
with the initial condition x(0) = 1
Solved for the current transient through an RC network that is driven by
5 V DC
the signal 5e-tU(t)
and plotted the solutions.
Solved the second order differential equation
dxdt2+2dxdt+2x = e-t
Solved the current transient through a series RLC circuit with R = 1, L = 1H and C = .001 F that is driven by
5 V DC
the signal 5e-tU(t)
Signals & System Lect 15 | Stable & Unstable Systems | Solved examples
ECT 204 SIGNALS AND SYSTEMS Topics covered 00:00 - Introduction to Stable & unstable Systems 01:08 - BIBO criteria 03:38 Problem No 1...

-
AIM: To familiarise with logic gate IC packages and to verify the truth tables of those gates COMPONENTS AND EQUIPMENTS REQUIRED: IC...
-
Question) Show the design of a simple sofa and then depict how the design changes when considering 1) aesthetics and 2) ergonomics into co...