티스토리 뷰

python/Lecture

[python][vscode] Signal Test Code

jinozpersona 2023. 11. 30. 09:37

 

 

vscode 하단 터미널(terminal) 탭에서 library 설치

# 앞에 $ 기호는 prompt를 나타냄

 

$ pip install numpy

$ pip install matplotlib 

 

ex0_quantization_signal.py
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0,11)
x = 0.85 ** t


plt.figure(figsize = (10,8))

# 1. Plotting Analog Signal
plt.subplot(2, 2, 1)
plt.title('Analog Signal', fontsize=20)

plt.plot(t, x, linewidth=3, label='x(t) = (0.85)^t')
plt.xlabel('t' , fontsize=15)
plt.ylabel('amplitude', fontsize=15)
plt.legend(loc='upper right')

# 2. Sampling and Plotting of Sampled signal
plt.subplot(2, 2, 2)
plt.title('Sampling', fontsize=20)
plt.plot(t, x, linewidth=3, label='x(t) = (0.85)^t')
n = t

markerline, stemlines, baseline = plt.stem(n, x, label='x(n) = (0.85)^n')
plt.setp(stemlines, 'linewidth', 3)
plt.xlabel('n' , fontsize = 15)
plt.ylabel('amplitude', fontsize = 15)
plt.legend(loc='upper right')

# 3. Quantization
plt.subplot(2, 2, 3)
plt.title('Quantization', fontsize = 20)

plt.plot(t, x, linewidth =3)
markerline, stemlines, baseline=plt.stem(n,x)
plt.setp(stemlines, 'linewidth', 3)
plt.xlabel('n', fontsize = 15)
plt.ylabel('Range of Quantizer', fontsize=15)

plt.axhline(y = 0.1, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.2, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.3, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.4, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.5, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.6, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.7, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.8, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.9, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 1.0, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)

plt.subplot(2, 2, 4)
plt.title('Quantized Signal', fontsize = 20)
xq = np.around(x,1)
markerline, stemlines, baseline = plt.stem(n,xq)
plt.setp(stemlines, 'linewidth', 3) 
plt.xlabel('n', fontsize = 15)
plt.ylabel('Range of Quantizer', fontsize=15)

plt.axhline(y = 0.1, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.2, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.3, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.4, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.5, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.6, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.7, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.8, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 0.9, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)
plt.axhline(y = 1.0, xmin = 0, xmax = 10, color = 'r', linewidth = 3.0)

plt.tight_layout()

plt.show()

 

 

ex1_analog2digital_example.py
import numpy as np
import matplotlib.pyplot as plt


def cap_charge_voltage(V0, time):
    return V0*(1 - np.exp(-time))

# continuous time
# sampling : descrete time
# f(t) = A*sin(2*pi*f*t) = A*sin(w*t)
t = np.arange(0.0,5.0,0.001)
V0 = 5 # 
s1 = cap_charge_voltage(V0,t)

ax1 = plt.subplot(211)
ax1.plot(t,s1,'-r',label='analog')
ax1.set_xlabel('time(tau=RC)')
ax1.set_ylabel('voltage')
ax1.axis('tight')
ax1.legend(loc="upper left")
ax1.grid()


dt = np.arange(0,5.5,0.5)
res_bit = 10
dV0 = 2**res_bit
s2 = cap_charge_voltage(dV0,dt)

ax2 = plt.subplot(212)
ax2.plot(dt,s2,'o',label='digit(10bit)')
for i in range(1,4,1):
    # ax2.text(dt[1],s2[1],str(s2[1]))
    ax2.text(dt[i],s2[i],str(s2[i]))
    ax2.axhline(y = round(s2[i],0), color = 'm', linestyle = '-') 
    ax2.text(dt[i]-0.5,round(s2[i],0)+30,str(round(s2[i],0)))
ax2.set_xticks(list(dt))
ax2.set_xlabel('descrete time')
ax2.set_ylabel('value')
ax2.axis('tight')
ax2.legend(loc="upper left")
ax2.grid()


plt.show()

 

 

 

ex2_realtime_signal.py

 

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 20])
x_sum = []
y_sum = []
y_sum_noise = []

for x in range(10):
    x_sum.append(x)
    # y = 2*(x**2)
    y = 2*x
    y_noise = np.random.randn()
    y_sum.append(y)
    y_sum_noise.append(y+y_noise)
    plt.scatter(x, y,label='y')
    plt.plot(x_sum, y_sum,'-bo',label='y_sum')
    plt.plot(x_sum, y_sum_noise,'-ro',label='y_sum_noise')
    plt.pause(0.5)
    plt.draw()
        
plt.grid()
plt.show()

 

 

 

ex3_sine_wave_sampling.py

 

import numpy as np
import matplotlib.pyplot as plt


def sin_wave(amp, freq, time):
    return amp*np.sin(2*np.pi*freq*time)

# continuous time
# sampling : descrete time
# f(t) = A*sin(2*pi*f*t) = A*sin(w*t)
t = np.arange(0.0,1.0,0.001)
f = 50 # frequency
A = 220 # Amplitude
s1 = sin_wave(A,f,t)
s2 = sin_wave(A/2,f*2,t)

ax1 = plt.subplot(311)
ax1.plot(t,s1,'-o',label='sin(t)')
ax1.set_xlabel('Angle [rad]')
ax1.set_ylabel('sin(x)')
ax1.axis('tight')
ax1.legend(loc="upper left")
ax1.grid()

ax2 = plt.subplot(312)
ax2.plot(t,s1+s2,'-o',label='sin(t)')
ax2.set_xlabel('Angle [rad]')
ax2.set_ylabel('sin(x)')
ax2.axis('tight')
ax2.legend(loc="upper left")
ax2.grid()



###### sampling ######
ax3 = plt.subplot(313)
x1 = np.linspace(0, 2*np.pi, 6)
x2 = np.linspace(0, 2*np.pi, 10)
x3 = np.linspace(0, 2*np.pi, 60)
x4 = np.linspace(0, 2*np.pi, 100)
ax3.plot(x1, np.sin(x1),'-ro',label='x1')
ax3.plot(x2, np.sin(x2),'-g*',label='x2')
ax3.plot(x3, np.sin(x3),'-bo',label='x3')
ax3.plot(x4, np.sin(x4),'-m*',label='x4')
ax3.set_xlabel('Angle [rad]')
ax3.set_ylabel('sin(x)')
ax3.axis('tight')
ax3.legend(loc="upper left")
ax3.grid()

plt.show()

 

 

 

Sinal Conditioning

 

vscode 하단 터미널(terminal) 탭에서 library 설치

# 앞에 $ 기호는 prompt를 나타냄

 

$ pip install pandas

$ pip install scipy

 

sample_data.csv를 다운로드하여 vscode 사용중인 폴더 안에 넣고 실행

sample_data.csv
0.14MB

 

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import savgol_filter as sg_filter
import scipy.constants as const
# from spectrum import Periodogram


filename = './sample_data.csv'
xydata = pd.read_csv(filename, names=["X", "Y"])
data_start = xydata.index[xydata["X"] == "XYDATA"].item()
data_end = xydata.index[xydata["X"] == "##### Extended Information"].item()
xydata = xydata.iloc[data_start + 1: data_end, :]
xydata.reset_index(inplace=True, drop=True)
xydata = xydata.astype("float64")
xydata["Y"] = xydata["Y"] / xydata["Y"].max()

x = list(xydata["X"])
x.pop()
y = list(xydata["Y"])
y.pop()

plt.figure(1)
# plot : transmission
ax1 = plt.subplot(211)
ax1.plot(x, y)
ax1.set_xlim(4000, 500)
ax1.set_ylim(None, 1.05)
ax1.set_xlabel('wavenumber [$\mathregular{cm^{-1}]}$')
ax1.set_ylabel('transmittance [a.u.]')
ax1.set_title('IR Spectrum transmittance',loc='left')
ax1.grid()

print(xydata)
# print(y)

# plot : absorbance
ax2 = plt.subplot(212)
x_lambda = 1/np.array(x)
con_y = list(-np.log10(y))
ax2.plot(x_lambda, con_y,'-c')
ax2.set_xlim(1/4000, 1/500)
ax2.set_ylim(None, 1.05)
ax2.set_xlabel("wavelengh $\lambda$ [cm]")
ax2.set_ylabel('absorbance')
ax2.set_title('IR Spectrum absorbance',loc='left')
ax2.grid()
# fig.tight_layout()

fig =plt.figure(2)
c = const.speed_of_light
x_f = np.array(x)*(c*10e2)/10e9 #GHz
y_sgf = sg_filter(y, 29, 2)
plt.plot(x_f,y,'-b',label='origin')
plt.plot(x_f,y_sgf,'-r',label='savitzky-golay filter')
plt.xlim(4000*(c*10e2)/10e9, 500*(c*10e2)/10e9)
plt.xlabel("Frequency [GHz]")
plt.ylabel('transmittance [a.u.]')
plt.title('Transmittance depend on Frequency',loc='left')
plt.legend(loc='lower left')
plt.grid()

plt.show()

 

 

 

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함