Added done Work
61
1.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import plot_lib
|
||||
import read_file
|
||||
import editing_data
|
||||
import matplotlib
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import scipy.signal as signal
|
||||
import os
|
||||
|
||||
voltage=[-8.9205,-6.704,-4.486,-2.266,-0.0205,2.225,4.445,6.662,8.88]
|
||||
|
||||
current = [-800, -600, -400, -200, 0, 200, 400, 600, 800]
|
||||
voltage_ideal = np.array(current)*(10/(9*100))
|
||||
|
||||
y = [voltage_ideal, voltage]
|
||||
x = current
|
||||
|
||||
labels = ["Ideale", "Messwerte"]
|
||||
|
||||
# plot_lib.plot_shared_xy(
|
||||
# x=x,
|
||||
# y_list=y,
|
||||
# xlabel="Strom (mA)",
|
||||
# ylabel="Spannung (V)",
|
||||
# title="Stromwandler Kennlinie",
|
||||
# show_points=True,
|
||||
# save_path="prak1/Stromwandler-Kennlinie.svg",
|
||||
# labels=labels
|
||||
# )
|
||||
figsize = (10, 6)
|
||||
plt.figure(figsize=figsize)
|
||||
plt.plot(x, y[1], label="Messwerte", color="purple", linestyle='--', marker='o', markersize=8)
|
||||
plt.plot(x, y[0], label="Ideale", color="red", linestyle='-', marker='', markersize=8)
|
||||
|
||||
plt.xlim(-800, 800)
|
||||
plt.ylim(-10, 10)
|
||||
plt.xlabel(r"Zeit ($\mu s$)")
|
||||
# plt.xlabel(r"Zeit (ms)")
|
||||
plt.ylabel("Voltage (V)")
|
||||
plt.title("Sprungantwort des Tiefpassfilters")
|
||||
plt.grid()
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
|
||||
save_path=f"prak1/Stromwandler-Kennlinie.svg"
|
||||
plt.savefig(save_path, format="svg")
|
||||
plt.show()
|
||||
|
||||
# diff = plot_lib.plot_difference(
|
||||
# x=x,
|
||||
# y1=y[0],
|
||||
# y2=y[1],
|
||||
# return_sum=True,
|
||||
# xlabel="Strom (mA)",
|
||||
# ylabel="Spannung (V)",
|
||||
# title="Stromwandler Messkennlinie - Idealkennlinie",
|
||||
# show_points=True,
|
||||
# save_path="prak1/Stromwandler-Vergleich-Kennlinie.svg"
|
||||
# )
|
||||
|
||||
# print(diff)
|
||||
101
2.py
Normal file
@@ -0,0 +1,101 @@
|
||||
import plot_lib
|
||||
import read_file
|
||||
import editing_data
|
||||
import matplotlib
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import scipy.signal as signal
|
||||
import os
|
||||
|
||||
matplotlib.use('Qt5Agg')
|
||||
|
||||
def plot1():
|
||||
volt_in, volt_out = read_file.read_xy_file("prak2/test.txt")
|
||||
|
||||
y = [volt_in, volt_out]
|
||||
x = volt_in
|
||||
|
||||
labels = ["Ideale Kennlinie", "Reale Kennlinie"]
|
||||
|
||||
plot_lib.plot_shared_xy(
|
||||
x=x,
|
||||
y_list=y,
|
||||
xlabel="Input Voltage (V)",
|
||||
ylabel="Output Voltage (V)",
|
||||
title="Kennlinie des Tiefpassfilters",
|
||||
show_points=True,
|
||||
save_path="prak2/kennlinie_tiefpass.svg",
|
||||
labels=labels
|
||||
)
|
||||
|
||||
diff = plot_lib.plot_difference(
|
||||
x=x,
|
||||
y1=y[0],
|
||||
y2=y[1],
|
||||
return_sum=True,
|
||||
xlabel="Input Voltage (V)",
|
||||
ylabel="Output Voltage (V)",
|
||||
title="Differenz der idealen und realen Kennlinie des Tiefpassfilters",
|
||||
show_points=True,
|
||||
save_path="prak2/kennlinie_tiefpass_diff.svg"
|
||||
)
|
||||
|
||||
print(diff)
|
||||
|
||||
def plot2():
|
||||
data_1k, indecies = read_file.read_data_with_indices("prak2/333_output1k.txt")
|
||||
data_3k, _ = read_file.read_data_with_indices("prak2/333_output3k.txt")
|
||||
data_5k, _ = read_file.read_data_with_indices("prak2/333_output5k.txt")
|
||||
data = [data_1k, data_3k, data_5k]
|
||||
labels = [r"$1\,\mathrm{k\Omega}$", r"$3\,\mathrm{k\Omega}$", r"$5\,\mathrm{k\Omega}$"]
|
||||
colors = ["red", "green", "blue"]
|
||||
indecies = indecies*1000
|
||||
ys = []
|
||||
xs = []
|
||||
|
||||
length = 169
|
||||
|
||||
figsize = (10, 6)
|
||||
plt.figure(figsize=figsize)
|
||||
|
||||
for i in range(len(data)):
|
||||
idxs = editing_data.detect_step_segments(data[i], diff_threshold=0.2, min_length=50)
|
||||
# print(i, idxs)
|
||||
y = data[i][idxs[0][0]:idxs[0][0]+length]
|
||||
x = np.arange(0, len(y)) / 48000 *1000000 # Zeit in mycrosekunden
|
||||
plt.plot(x, y, label=labels[i] + " (Messung)", color=colors[i], linestyle='--', marker='x', markersize=8)
|
||||
ys.append(y)
|
||||
xs.append(x)
|
||||
|
||||
C = 100e-9
|
||||
R = [1e3, 3e3, 5e3]
|
||||
|
||||
t = np.linspace(0, 0.0035, 1000)
|
||||
|
||||
for i in range(len(R)):
|
||||
Rs = R[i]
|
||||
label = labels[i]
|
||||
num = [5]
|
||||
den = [Rs*C, 1]
|
||||
system = signal.TransferFunction(num, den)
|
||||
t_out, y = signal.step(system, T=t)
|
||||
t_out = t_out * 1000 * 1000
|
||||
plt.plot(t_out, y, label=label + " (Ideal)", color=colors[i])
|
||||
|
||||
plt.xlim(0, 1.5*1000)
|
||||
plt.ylim(0, 5.5)
|
||||
plt.xlabel(r"Zeit ($\mu s$)")
|
||||
# plt.xlabel(r"Zeit (ms)")
|
||||
plt.ylabel("Voltage (V)")
|
||||
plt.title("Sprungantwort des Tiefpassfilters")
|
||||
plt.grid()
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
|
||||
save_path=f"prak2/tiefpass_mult_r.svg"
|
||||
plt.savefig(save_path, format="svg")
|
||||
plt.show()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# plot1()
|
||||
plot2()
|
||||
435
4.py
Normal file
@@ -0,0 +1,435 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import mdt
|
||||
|
||||
def remove_useless_data(data, idx):
|
||||
new_data = []
|
||||
new_idx = []
|
||||
for i in range(len(data)-1):
|
||||
if i == 0:
|
||||
new_data.append(data[i])
|
||||
new_idx.append(idx[i])
|
||||
elif i == len(data)-1:
|
||||
new_data.append(data[i])
|
||||
new_idx.append(idx[i])
|
||||
new_data.append(data[i+1])
|
||||
new_idx.append(idx[i+1])
|
||||
elif(not(data[i-1]==data[i]==data[i+1])):
|
||||
new_data.append(data[i])
|
||||
new_idx.append(idx[i])
|
||||
return new_data, new_idx
|
||||
|
||||
|
||||
def remove_useless_data2(data, idx):
|
||||
data = np.asarray(data)
|
||||
idx = np.asarray(idx)
|
||||
|
||||
# Identify flat regions of length >= 3
|
||||
mid = np.ones(len(data), dtype=bool)
|
||||
mid[1:-1] = ~((data[:-2] == data[1:-1]) & (data[1:-1] == data[2:]))
|
||||
|
||||
# Apply the mask
|
||||
return data[mid], idx[mid]
|
||||
|
||||
def theoretische_ADU_kennlinie(save_path=None, u_min=-5, u_max=5, N=3, alone=True):
|
||||
L = 2**N
|
||||
U_lsb = (u_max - u_min) / (L-1)
|
||||
|
||||
x = [u_min]
|
||||
y = [0]
|
||||
|
||||
for i in range(L):
|
||||
if i == 0:
|
||||
y.append(0)
|
||||
x.append(u_min+(U_lsb/2))
|
||||
elif i == L-1:
|
||||
y.append(y[i]+1)
|
||||
x.append(u_max)
|
||||
else:
|
||||
y.append(y[i]+1)
|
||||
x.append(x[i]+U_lsb)
|
||||
|
||||
|
||||
print(f"x: {x}")
|
||||
print(f"y: {y}")
|
||||
|
||||
if alone:
|
||||
plt.figure()
|
||||
|
||||
plt.step(x, y, marker="", linewidth=0.5, label=f"{N}-Bit AD-Umsetzer, $U_{{LSB}}$ = {U_lsb:.3f} V (Theorie)")
|
||||
|
||||
if alone:
|
||||
plt.xlabel("Eingangsspannung U [V]")
|
||||
plt.ylabel("Ausgangscode")
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
if save_path:
|
||||
plt.savefig(save_path, dpi=300)
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
# def theoretische_ADU_kennlinie(save_path, u_min=-5, u_max=5, N=3):
|
||||
# y = []
|
||||
# y.append(np.int64(0))
|
||||
# for value in np.arange((N**2)-1):
|
||||
# y.append(value)
|
||||
# y.append(y[len(y)-1]+1)
|
||||
|
||||
# U_lsb = (u_max-u_min)/((2**N)-1)
|
||||
|
||||
# x = []
|
||||
# x.append(u_min)
|
||||
# x.append(u_min+U_lsb/2)
|
||||
# for _ in range(len(y)-4):
|
||||
# x.append(x[len(x)-1]+U_lsb)
|
||||
# x.append(x[len(x)-1]+U_lsb)
|
||||
# x.append(u_max)
|
||||
|
||||
# # x_values = []
|
||||
# # double_inner(x, x_values, len(x))
|
||||
|
||||
# # y_values = []
|
||||
# # double_inner(y, y_values, len(y))
|
||||
|
||||
|
||||
# # print(f"step_length: {U_lsb}")
|
||||
# # print(f"x[{len(x)}]: {x}")
|
||||
# # print(f"y[{len(y)}]: {y}")
|
||||
|
||||
# # plot something
|
||||
# plt.step(x, y, marker="", label=f"{N}"+"-Bit AD-Umsetzers mit $U_{LSB}$ = " + str(np.round(U_lsb, 3))+ " (Theorie)")
|
||||
|
||||
# # format ticks as binary
|
||||
# # ax.set_yticks(y)
|
||||
# # ax.set_yticklabels([format(i, "03b") for i in y])
|
||||
# # plt.xticks(np.arange(int(np.floor(np.min(x))), int(np.ceil(np.max(x)))+1, 1))
|
||||
|
||||
# # plt.xlim(u_min-U_lsb/2, u_max+U_lsb/2)
|
||||
|
||||
# # plt.xlabel("U [V]")
|
||||
# # plt.ylabel("Codes [bit]")
|
||||
|
||||
# # plt.title(f"Kennlinie einer {N}Bit-ADU")
|
||||
# # plt.grid()
|
||||
# # plt.legend()
|
||||
# # plt.tight_layout()
|
||||
# # if save_path:
|
||||
# # plt.savefig(save_path, format="svg")
|
||||
# # plt.show()
|
||||
|
||||
def manuell_adu(data_file, save_path):
|
||||
matrix = np.loadtxt(data_file, delimiter=",", skiprows=1, dtype=str)
|
||||
matrix = np.char.strip(matrix) # remove leading/trailing spaces
|
||||
|
||||
von = matrix[:, 0].astype(float)
|
||||
bis = matrix[:, 1].astype(float)
|
||||
code = matrix[:, 2]
|
||||
|
||||
x = []
|
||||
|
||||
for i in range(len(von)):
|
||||
if(i !=0):
|
||||
x.append(bis[i])
|
||||
else:
|
||||
x.append(von[i])
|
||||
x.append(bis[i])
|
||||
y = [np.int64(0)]
|
||||
y.extend(np.arange(len(code)))
|
||||
|
||||
# print(f"x: {x}")
|
||||
# print(f"y: {y}")
|
||||
|
||||
plt.step(x, y, marker="x", linewidth=0.5, label=f"4"+"-Bit AD-Umsetzers mit $U_{LSB}$ = " + "0.66 V (Manuell)")
|
||||
|
||||
# plt.yticks(y, [format(i, "03b") for i in y])
|
||||
|
||||
# plt.xlim(np.min(x)-(x[1]-x[0]), np.max(x)+(x[1]-x[0]))
|
||||
|
||||
# plt.xlabel("U [V]")
|
||||
# plt.ylabel("Codes [bit]")
|
||||
|
||||
# plt.title(f"Kennlinie einer 4Bit-ADU")
|
||||
# plt.grid()
|
||||
# plt.legend()
|
||||
# plt.tight_layout()
|
||||
# plt.savefig(save_path, format="svg")
|
||||
# plt.show()
|
||||
|
||||
def automatisch_adu(data_file, save_path, u_min=-5.5, u_max=5.5):
|
||||
data = np.loadtxt(data_file, dtype=np.float64)
|
||||
# print(data)
|
||||
start = 0
|
||||
multiple = 0
|
||||
max_mult=10
|
||||
for value in data:
|
||||
start+=1
|
||||
if(value==0):
|
||||
multiple+=1
|
||||
else:
|
||||
multiple=0
|
||||
if multiple==max_mult:
|
||||
start-=max_mult
|
||||
break
|
||||
|
||||
data = data[start:]
|
||||
|
||||
end = 0
|
||||
multiple = 0
|
||||
for value in data:
|
||||
end+=1
|
||||
if(value>0):
|
||||
multiple+=1
|
||||
else:
|
||||
multiple=0
|
||||
if multiple==max_mult:
|
||||
end-=max_mult
|
||||
break
|
||||
|
||||
data = data[np.int64(end/2):]
|
||||
|
||||
start = 0
|
||||
for value in data:
|
||||
start+=1
|
||||
if(value>=15):
|
||||
break
|
||||
|
||||
data = data[:np.int64(start+end/2)]
|
||||
|
||||
points=0
|
||||
correct=False
|
||||
for value in data:
|
||||
if value > 1 or correct==True:
|
||||
correct = True
|
||||
points +=1
|
||||
if correct==True and value >=3:
|
||||
break
|
||||
|
||||
step_time=(points)/40000
|
||||
|
||||
U_LSB = (u_max-u_min)*2 * step_time
|
||||
|
||||
# print(f"U_LSB: {U_LSB}")
|
||||
|
||||
y = np.int64(data)
|
||||
idx = np.arange(0,len(data))
|
||||
|
||||
y, idx = remove_useless_data2(y, idx)
|
||||
|
||||
# x=np.subtract(np.multiply(np.divide(idx, 39500),22), 5.5)
|
||||
x=np.subtract(np.multiply(np.divide(idx, 40000),22), 5.5)
|
||||
|
||||
plt.step(x, y, marker="", linewidth=0.5, label=f"4"+"-Bit AD-Umsetzers mit $U_{LSB}$ = " + f"{np.round(U_LSB,3)} V (Automatisiert)")
|
||||
|
||||
# plt.yticks(y, [format(i, "03b") for i in y])
|
||||
# plt.xticks(np.arange(int(np.floor(x.min())), int(np.ceil(x.max()))+1, 1))
|
||||
|
||||
# plt.xlim(-6, 6)
|
||||
|
||||
# plt.xlabel("t [s]")
|
||||
# plt.ylabel("Codes [bit]")
|
||||
|
||||
# plt.title(f"Kennlinie einer 4Bit-ADU")
|
||||
# plt.grid()
|
||||
# plt.legend()
|
||||
# plt.tight_layout()
|
||||
# plt.savefig(save_path, format="svg")
|
||||
# plt.show()
|
||||
|
||||
def quantisierungsrauschen_plot(data_file):
|
||||
data = np.loadtxt(data_file, dtype=np.float64)
|
||||
x = np.arange(0, len(data))
|
||||
# # print(x)
|
||||
# plt.plot(x, data)
|
||||
return data, x
|
||||
|
||||
def plot_sine_wave(amplitude=1, frequency=1, phase=0, t_start=0, t_end=2*np.pi, points=1000,
|
||||
x_shift=0, y_shift=0, color='blue', linewidth=1.5, title='Sine Wave', xlabel='Time', ylabel='Amplitude'):
|
||||
"""
|
||||
Plots a sine wave with customizable parameters.
|
||||
|
||||
Parameters:
|
||||
- amplitude: Amplitude of the sine wave
|
||||
- frequency: Frequency in Hz
|
||||
- phase: Phase shift in radians
|
||||
- t_start: Start of x-axis
|
||||
- t_end: End of x-axis
|
||||
- points: Number of points in the plot
|
||||
- x_shift: Shift the wave along x-axis
|
||||
- y_shift: Shift the wave along y-axis
|
||||
- color: Line color
|
||||
- linewidth: Line thickness
|
||||
- title: Plot title
|
||||
- xlabel, ylabel: Axis labels
|
||||
"""
|
||||
|
||||
# Generate x-axis values
|
||||
t = np.linspace(t_start, t_end, points)
|
||||
|
||||
# Compute sine wave with phase and shifts
|
||||
y = amplitude * np.sin(2 * np.pi * frequency * t + phase) + y_shift
|
||||
t = t + x_shift # shift x-axis if needed
|
||||
|
||||
return y, t
|
||||
|
||||
|
||||
def vorbereitung():
|
||||
theoretische_ADU_kennlinie(save_path="prak4/3-bit-adu.svg")
|
||||
|
||||
def task1():
|
||||
automatisch_adu("prak4/prak4/ADU-Kennlinie_automatisch.csv", f"prak4/4-bit-adu-auto.svg")
|
||||
theoretische_ADU_kennlinie(N=4, save_path="prak4/prak4/4-bit-adu-theorie.svg", alone=False)
|
||||
manuell_adu("prak4/prak4/ADU-Kennlinie_manuell.csv", f"prak4/4-bit-adu-manuell.svg")
|
||||
|
||||
plt.plot([-5,5],[0,15], marker="", linewidth=0.5, label=r"$\infty$-Bit ADU (Theoretisch)")
|
||||
|
||||
plt.yticks(np.arange(0,15), [format(i, "03b") for i in np.arange(0,15)])
|
||||
plt.xticks(np.arange(int(np.floor(-6)), int(np.ceil(6))+1, 1))
|
||||
|
||||
plt.xlim(-5.5, 5.5)
|
||||
|
||||
plt.xlabel("U [V]")
|
||||
plt.ylabel("Codes [bit]")
|
||||
|
||||
plt.title(f"Kennlinie einer 4Bit-ADU")
|
||||
plt.grid()
|
||||
plt.legend(loc='upper left')
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"prak4/4bit-adu-kennlinie.svg", format="svg")
|
||||
plt.show()
|
||||
|
||||
def cut_fitting(idx_target, data, idx_source):
|
||||
start = np.where(idx_source == idx_target[0])[0]
|
||||
end = np.where(idx_source == idx_target[len(idx_target)-1])[0][0]
|
||||
|
||||
if len(start)>1:
|
||||
for v in start:
|
||||
if v + len(idx_target) == end:
|
||||
start = v
|
||||
break
|
||||
|
||||
idx_source = idx_source[start:end]
|
||||
data = data[start:end]
|
||||
|
||||
|
||||
return data, idx_source
|
||||
|
||||
def get_smallest_sin_dif(data, idx):
|
||||
x_shift = 0
|
||||
sum = 50000000
|
||||
for i in np.arange(-1700, -1500):
|
||||
ideal, t = plot_sine_wave(amplitude=5, frequency=15, t_start=0, t_end=1.5*40000, points=60000, x_shift=i)
|
||||
ideal, t = cut_fitting(idx, ideal, np.int64(t))
|
||||
if np.sum(np.abs(np.abs(ideal)-np.abs(data)))<sum:
|
||||
sum = np.sum(np.abs(np.abs(ideal)-np.abs(data)))
|
||||
x_shift = i
|
||||
print(f"x_shift: {x_shift}")
|
||||
print(f"sum: {sum}")
|
||||
|
||||
ideal, t = plot_sine_wave(amplitude=5, frequency=15, t_start=0, t_end=1.5*40000, points=60000, x_shift=x_shift)
|
||||
ideal, t = cut_fitting(idx, ideal, np.int64(t))
|
||||
|
||||
return ideal, t
|
||||
|
||||
def plot_both_sin(data, idx, ideal):
|
||||
plt.plot(idx, data, label=f'Gemessener Sinus')
|
||||
plt.plot(idx, ideal, label=f'Idealer Sinus')
|
||||
|
||||
plt.xlim(left=0, right=1)
|
||||
|
||||
plt.xlabel("t [s]")
|
||||
plt.ylabel("u [V]")
|
||||
|
||||
plt.title(f"Gemessenes und Ideales Signal")
|
||||
plt.grid()
|
||||
plt.legend(loc='upper left')
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"prak4/sin_normal.svg", format="svg")
|
||||
plt.show()
|
||||
|
||||
def plot_diff(data, idx, ideal):
|
||||
|
||||
plt.plot(idx, data-ideal)
|
||||
plt.xlabel("t [s]")
|
||||
plt.ylabel("u [V]")
|
||||
|
||||
plt.title(f"Quantisierungsrauschen im Beispiel einer Sinus-Funktion")
|
||||
plt.grid()
|
||||
# plt.legend(loc='upper left')
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"prak4/sin_all.svg", format="svg")
|
||||
plt.show()
|
||||
|
||||
def plot_all_sin(data, idx, ideal):
|
||||
plt.plot(idx, data, label=f'Gemessener Sinus')
|
||||
plt.plot(idx, ideal, label=f'Idealer Sinus')
|
||||
N=len(idx)
|
||||
U_Rauschen = (data-ideal)
|
||||
plt.plot(idx, U_Rauschen, label=f'Quantisierungsrauschen')
|
||||
U_eff = np.sqrt(np.multiply(np.divide(1, N), np.sum(np.square(U_Rauschen))))
|
||||
|
||||
print(f"U_eff: {U_eff}")
|
||||
plt.plot([idx[0], idx[len(idx)-1]], [U_eff, U_eff], label=f'Effektivwert des Quantisierungsrauschens')
|
||||
plt.xlabel("t [s]")
|
||||
plt.ylabel("u [V]")
|
||||
|
||||
plt.xlim(left=0, right=0.2)
|
||||
|
||||
plt.title(f"Quantisierungsrauschen im Beispiel einer Sinus-Funktion")
|
||||
plt.grid()
|
||||
plt.legend(loc='upper left')
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"prak4/sin_all.svg", format="svg")
|
||||
plt.show()
|
||||
|
||||
def task2():
|
||||
plt.figure(figsize=(8,4))
|
||||
data, idx = quantisierungsrauschen_plot(f"prak4/prak4/Quantisierungsrauschen.csv")
|
||||
ideal, t = get_smallest_sin_dif(data, idx)
|
||||
# plot_both_sin(data, np.divide(idx, 40000), ideal)
|
||||
# plot_diff(data, np.divide(idx, 40000), ideal)
|
||||
plot_all_sin(data, np.divide(idx, 40000), ideal)
|
||||
|
||||
def plot_data_spektrum(data_file, rate, save_path, xlim_start=0, xlim_end=0):
|
||||
data = np.loadtxt(data_file, dtype=np.float64)
|
||||
f,u = mdt.spectrum(data, rate)
|
||||
fig, (ax1,ax2) = plt.subplots(2)
|
||||
ax1.plot(np.divide(np.arange(0, len(data)), rate),data)
|
||||
ax2.plot(f,u)
|
||||
|
||||
if xlim_end !=0:
|
||||
ax1.set_xlim(xlim_start, xlim_end)
|
||||
|
||||
# Titles for each subplot
|
||||
ax1.set_title("Zeitsignal")
|
||||
ax2.set_title("Frequenz Spektrum")
|
||||
|
||||
# X/Y labels for each subplot
|
||||
ax1.set_xlabel("t [s]")
|
||||
ax1.set_ylabel("U [V]")
|
||||
|
||||
ax2.set_xlabel("Frequency [Hz]")
|
||||
ax2.set_ylabel("Magnitude")
|
||||
|
||||
# Overall title
|
||||
# fig.suptitle(f"Signal analyse bei {np.divide(rate, 1000)} kHz Abtastrate", fontsize=16)
|
||||
|
||||
# Layout to prevent overlap
|
||||
plt.tight_layout()
|
||||
fig.subplots_adjust(top=0.88) # make space for suptitle
|
||||
plt.savefig(save_path, format="svg")
|
||||
plt.show()
|
||||
|
||||
def task3():
|
||||
rates = [10000, 12500, 15000, 17500, 20000, 25000, 30000, 35000, 40000]
|
||||
for rate in rates:
|
||||
plot_data_spektrum(f"prak4/prak4/Aliasing_{rate}.csv", rate, f"prak4/aliasing_{rate}.svg")
|
||||
|
||||
def task4():
|
||||
rates = [10000, 44000]
|
||||
for rate in rates:
|
||||
plot_data_spektrum(f"prak4/prak4/Aliasingfilter_mit_box_{rate}.csv", rate, f"prak4/aliasing_mit_filter_{rate}.svg", 0, 0.01)
|
||||
plot_data_spektrum(f"prak4/prak4/Aliasingfilter_ohne_box_{rate}.csv", rate, f"prak4/aliasing_ohne_filter_{rate}.svg", 0, 0.01)
|
||||
|
||||
if __name__ == '__main__':
|
||||
task3()
|
||||
249
5.py
Normal file
@@ -0,0 +1,249 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
colors = {
|
||||
"U": "tab:blue", # Voltage
|
||||
"I": "tab:orange", # Current
|
||||
"P": "tab:green", # Real power
|
||||
"S": "tab:red", # Apparent power
|
||||
"Q": "tab:purple" # Reactive power
|
||||
}
|
||||
|
||||
def convert_voltage(v):
|
||||
Vu = np.divide(10, 566)
|
||||
return np.divide(v, Vu)
|
||||
|
||||
def convert_back_voltage(v):
|
||||
Vu = np.divide(10, 566)
|
||||
return np.multiply(v, Vu)
|
||||
|
||||
def convert_current(i):
|
||||
Vi = np.divide(10, 0.9)
|
||||
return np.divide(i, Vi)
|
||||
|
||||
def convert_back_current(i):
|
||||
Vi = np.divide(10, 0.9)
|
||||
return np.multiply(i, Vi)
|
||||
|
||||
def convert_power(p):
|
||||
Vu = np.divide(10, 566)
|
||||
Vi = np.divide(10, 0.9)
|
||||
p = np.divide(p, Vu)
|
||||
return np.divide(p, Vi)
|
||||
|
||||
def convert_back_power(p):
|
||||
Vu = np.divide(10, 566)
|
||||
Vi = np.divide(10, 0.9)
|
||||
p = np.multiply(p, Vu)
|
||||
return np.multiply(p, Vi)
|
||||
|
||||
class Messung5:
|
||||
def __init__(self, data, name):
|
||||
self.name = name
|
||||
if name == "Leuchtstoffröhre":
|
||||
self.voltage = np.multiply(convert_voltage(data[0]),np.sqrt(3))
|
||||
else:
|
||||
self.voltage = convert_voltage(data[0])
|
||||
self.current = convert_current(data[1])
|
||||
|
||||
self.u_rms = np.sqrt(np.mean(np.square(self.voltage)))
|
||||
self.i_rms = np.sqrt(np.mean(np.square(self.current)))
|
||||
|
||||
self.pltvoltage = self.voltage[0:1200]
|
||||
self.pltcurrent = self.current[0:1200]
|
||||
|
||||
self.P = np.mean(self.voltage * self.current)
|
||||
|
||||
self.S = self.u_rms * self.i_rms
|
||||
|
||||
self.Q = np.sqrt(np.square(self.S) - np.square(self.P))
|
||||
|
||||
self.cos_phi = self.P / self.S
|
||||
|
||||
def augenblickleistung(self):
|
||||
print(f"{self.name}:\nAugenblickleistung: {self.u_eff * self.i_eff}\n")
|
||||
|
||||
def print(self):
|
||||
print(
|
||||
f"{self.name}:\n"
|
||||
f"cos_phi1\t = {self.cos_phi}\n"
|
||||
f"Scheinleistung\t = {self.S} W\n"
|
||||
f"Wirkleistung\t = {self.P} W\n"
|
||||
f"Blindleistung\t = {self.Q} W\n"
|
||||
)
|
||||
|
||||
def plot(self, show=False):
|
||||
plt.plot(self.pltvoltage, label='voltage in V')
|
||||
plt.plot(self.pltcurrent*1000, label='current in mA')
|
||||
plt.plot(self.P, label='Leistung in W')
|
||||
plt.legend()
|
||||
plt.grid()
|
||||
plt.xlabel('time in ms')
|
||||
plt.ylabel('value')
|
||||
if show:
|
||||
plt.show()
|
||||
|
||||
def task_5_4_1():
|
||||
birne = Messung5(np.load('prak5/5.4.1_glueh.npy'), "Glühbirne")
|
||||
led = Messung5(np.load('prak5/5.4.1_LED.npy'), "LED")
|
||||
roehre = Messung5(np.load('prak5/5.4.1_Leuchtstoffroehre.npy'), "Leuchtstoffröhre")
|
||||
|
||||
# birne.plot(show=True)
|
||||
|
||||
birne.print()
|
||||
led.print()
|
||||
roehre.print()
|
||||
|
||||
class Messwerte:
|
||||
def __init__(self, name, p, q, u_eff, i_eff):
|
||||
self.name = name
|
||||
self.u_eff = convert_voltage(u_eff)
|
||||
self.i_eff = convert_current(i_eff)
|
||||
self.p = convert_power(p)
|
||||
self.q = np.divide(convert_power(q), np.sqrt(3))
|
||||
self.s = self.u_eff * self.i_eff
|
||||
self.q_calc = np.sqrt((np.square(self.s)-np.square(self.p)))
|
||||
|
||||
def print(self):
|
||||
print(
|
||||
f"{self.name}:\n"
|
||||
f"\t Spannung\t\t = {self.u_eff} V\n"
|
||||
f"\t Strom\t\t\t = {self.i_eff} A\n"
|
||||
f"\t Wirkleistung\t\t = {self.p} W\n"
|
||||
f"\t Blindleistung\t\t = {self.q} var\n"
|
||||
f"\t Scheinleistung\t\t = {self.s} AV\n"
|
||||
f"\t Blindleistung Mess\t = {self.q_calc} var\n"
|
||||
)
|
||||
|
||||
def task_5_4_2():
|
||||
glueh = Messwerte("Glühlampe", 10.9, 0.06, 3.94, 2.801)
|
||||
led = Messwerte("LED", 1.15, 0.25, 3.94, 0.4)
|
||||
roehre = Messwerte("Leuchtstoffröhre", 4.57, 23, 3.93, 3.8)
|
||||
|
||||
glueh.print()
|
||||
led.print()
|
||||
roehre.print()
|
||||
|
||||
def dimmer_messung(ax):
|
||||
delta_t = np.divide([1.8, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2], 1.31)
|
||||
U_eff=np.empty(len(delta_t));
|
||||
U_eff.fill(3.93)
|
||||
U_eff = convert_voltage(U_eff)
|
||||
I_eff = [2.794, 2.729, 2.57, 2.38, 2.219, 1.82, 1.443]
|
||||
I_eff = convert_current(I_eff)
|
||||
P = [10.8, 10.1, 8.7, 6.95, 5.68, 3.18, 1.62]
|
||||
P = convert_power(P)
|
||||
S = np.multiply(I_eff, U_eff)
|
||||
Q = np.sqrt(np.square(S)-np.square(P))
|
||||
ax.plot(anschnittzeit_zu_winkel(delta_t), np.divide(U_eff, 10), label='Spannung gemessen in daV', linestyle='--', marker='x', markersize=8, color=colors["U"])
|
||||
ax.plot(anschnittzeit_zu_winkel(delta_t), np.multiply(100, I_eff), label='Strom gemessen in cA', linestyle='--', marker='x', markersize=8, color=colors["I"])
|
||||
ax.plot(anschnittzeit_zu_winkel(delta_t), P, label='Wirkleistung gemessen in W', linestyle='--', marker='x', markersize=8, color=colors["P"])
|
||||
ax.plot(anschnittzeit_zu_winkel(delta_t), S, label='Scheinleistung gemessen in VA', linestyle='--', marker='x', markersize=8, color=colors["S"])
|
||||
ax.plot(anschnittzeit_zu_winkel(delta_t), Q, label='Blindleistung gemessen in var', linestyle='--', marker='x', markersize=8, color=colors["Q"])
|
||||
# plt.legend()
|
||||
# plt.grid()
|
||||
# plt.xlabel('Anchnitt in °')
|
||||
# plt.ylabel('Wert in cA/W/VA/var')
|
||||
# plt.savefig(f"prak5/dimmer_mesung.svg", format="svg")
|
||||
# plt.show()
|
||||
|
||||
def generate_sin_wave(frequency, amplitude, duration, phase_shift=0, anschnitt=0):
|
||||
sample_rate = 44100
|
||||
num_samples = int(duration * sample_rate)
|
||||
t = np.linspace(0, duration, num_samples)
|
||||
omega = 2 * np.pi * frequency
|
||||
y = amplitude * np.sin(omega * t + phase_shift)
|
||||
if anschnitt > 0:
|
||||
phi = np.mod(omega * t + phase_shift, np.pi)
|
||||
conduction = phi >= anschnitt
|
||||
y = np.where(conduction, y, 0)
|
||||
|
||||
return t, y
|
||||
|
||||
def anschnittwinkel_zu_zeit(winkel):
|
||||
f = 50
|
||||
T = 1/f
|
||||
|
||||
theta = np.deg2rad(winkel)
|
||||
t_sec = np.divide(theta, (2*np.pi) * T)
|
||||
t_ms = t_sec * 1000
|
||||
return t_ms
|
||||
|
||||
def anschnittrad_zu_zeit(rad):
|
||||
f = 50
|
||||
T = 4*1/f
|
||||
theta = rad
|
||||
t_sec = np.divide(theta, (2*np.pi) * T)
|
||||
t_ms = t_sec * 1000
|
||||
return t_ms
|
||||
|
||||
def anschnittzeit_zu_winkel(t_ms):
|
||||
f = 50
|
||||
T = 1/f
|
||||
t_sec = np.divide(t_ms, 1000)
|
||||
theta = t_sec * (2*np.pi) / T
|
||||
return np.rad2deg(theta)
|
||||
|
||||
def anschnittzeit_zu_rad(t_ms):
|
||||
f = 50
|
||||
T = 1/f
|
||||
t_sec = np.divide(t_ms, 1000)
|
||||
theta = t_sec * (2*np.pi) / T
|
||||
return theta
|
||||
|
||||
def calc_P(u_t, i_t, T):
|
||||
return np.divide(np.sum(u_t * i_t), T)
|
||||
|
||||
def dimmer_theorie(ax):
|
||||
f = 50
|
||||
T = 1/f
|
||||
U = 222.438
|
||||
theta_winkel = np.arange(0, 180, 1)
|
||||
theta = np.deg2rad(theta_winkel)
|
||||
t, u = generate_sin_wave(f, U*np.sqrt(2), T)
|
||||
|
||||
v_hat = np.max(u)
|
||||
V_RMS = np.divide(v_hat, np.sqrt(2))
|
||||
|
||||
U_RMS=np.empty(len(theta));
|
||||
U_RMS.fill(V_RMS)
|
||||
|
||||
I = 0.25209000000000004
|
||||
I_RMS = []
|
||||
P = []
|
||||
for angle in theta:
|
||||
_, i = generate_sin_wave(f, np.multiply(I, np.sqrt(2)), T, anschnitt=angle)
|
||||
i_eff = np.sqrt(np.mean(np.square(i)))
|
||||
I_RMS.append(i_eff)
|
||||
P.append(np.mean(i * u))
|
||||
|
||||
S = np.multiply(U_RMS, I_RMS)
|
||||
Q = np.sqrt(np.square(S)-np.square(P))
|
||||
ax.plot(theta_winkel, np.divide(U_RMS, 10), label='Voltage in daV', color=colors["U"])
|
||||
ax.plot(theta_winkel, np.multiply(I_RMS, 100), label='Strom in cA', color=colors["I"])
|
||||
ax.plot(theta_winkel, P, label='Wirkleistung in W', color=colors["P"])
|
||||
ax.plot(theta_winkel, S, label='Scheinleistung in VA', color=colors["S"])
|
||||
ax.plot(theta_winkel, Q, label='Blindleistung in var', color=colors["Q"])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# task_5_4_1()
|
||||
# task_5_4_2()
|
||||
|
||||
fig, ax = plt.subplots(figsize=(8, 5))
|
||||
dimmer_messung(ax)
|
||||
dimmer_theorie(ax)
|
||||
|
||||
ax.grid()
|
||||
ax.set_xlabel('Anchnitt in °')
|
||||
ax.set_ylabel('Wert in daV/cA/W/var')
|
||||
|
||||
ax.legend(
|
||||
loc="upper center",
|
||||
bbox_to_anchor=(0.5, -0.18), # push legend below axes
|
||||
ncol=3, # spread entries horizontally
|
||||
frameon=False
|
||||
)
|
||||
plt.tight_layout()
|
||||
plt.savefig("prak5/dimmer.svg", format="svg", bbox_inches="tight")
|
||||
plt.show()
|
||||
29
6.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
gewicht = [50, 100, 150, 200, 250, 300, 350]
|
||||
V = np.divide(5, 0.002)
|
||||
|
||||
def viertelmessbrücke_gemessen():
|
||||
U_filtered = [0.113, 0.214, 0.316, 0.428, 0.524, 0.640, 0.727]
|
||||
m = np.divide(U_filtered, gewicht)
|
||||
print(m)
|
||||
print(gewicht)
|
||||
# plt.plot(m, label='Gewicht')
|
||||
# plt.plot(gewicht, label='Gewicht angegeben')
|
||||
# plt.legend()
|
||||
# plt.grid()
|
||||
# plt.xlabel('time in ms')
|
||||
# plt.ylabel('value')
|
||||
# plt.show()
|
||||
|
||||
|
||||
# def viertelmessbrücke_theorie():
|
||||
# m = #np.divide(Ebh², 6lgk)
|
||||
|
||||
def vollmessbrücke():
|
||||
U_filtered = [0.415, 0.893, 1.267, 1.707, 2.140, 2.590, 2.993]
|
||||
|
||||
if __name__ == '__main__':
|
||||
viertelmessbrücke_gemessen()
|
||||
#vollmessbrücke()
|
||||
101
editing_data.py
Normal file
@@ -0,0 +1,101 @@
|
||||
import numpy as np
|
||||
|
||||
def detect_step_segments(signal,
|
||||
diff_threshold=0.05,
|
||||
min_length=20):
|
||||
"""
|
||||
Erkennt automatisch Step-Up/Step-Down-Segmente aus einem gemessenen Tiefpass-Signal.
|
||||
Arbeitet über die erste Ableitung statt über absolute Schwellen.
|
||||
|
||||
signal : 1D array
|
||||
diff_threshold : float
|
||||
Minimale Änderung pro Sample, um einen Step zu erkennen.
|
||||
Für deine Daten funktioniert ~0.05 gut.
|
||||
min_length : int
|
||||
Minimale Länge eines Segments (Samples).
|
||||
|
||||
Returns:
|
||||
list of (start_idx, end_idx)
|
||||
"""
|
||||
|
||||
s = np.asarray(signal)
|
||||
diff = np.diff(s)
|
||||
|
||||
# Step-Up dort, wo diff stark positiv ist
|
||||
ups = np.where(diff > diff_threshold)[0]
|
||||
|
||||
# Step-Down dort, wo diff stark negativ ist
|
||||
downs = np.where(diff < -diff_threshold)[0]
|
||||
|
||||
segments = []
|
||||
|
||||
# Beide Listen sind ungeordnet, aber Step-Up sollte vor Step-Down kommen
|
||||
up_idx = 0
|
||||
down_idx = 0
|
||||
|
||||
while up_idx < len(ups) and down_idx < len(downs):
|
||||
start = ups[up_idx]
|
||||
|
||||
# Nimm das nächste Down-Event, das nach dem Start liegt
|
||||
while down_idx < len(downs) and downs[down_idx] <= start:
|
||||
down_idx += 1
|
||||
|
||||
if down_idx >= len(downs):
|
||||
break
|
||||
|
||||
end = downs[down_idx]
|
||||
|
||||
if end - start >= min_length:
|
||||
segments.append((start, end))
|
||||
|
||||
up_idx += 1
|
||||
down_idx += 1
|
||||
|
||||
return merge_close_segments(segments)
|
||||
|
||||
def merge_close_segments(segments, max_start_gap=10, max_end_gap=10):
|
||||
"""
|
||||
Fasst Segmente zusammen, deren Starts und Ends nahe beieinander liegen.
|
||||
|
||||
segments : list of (start, end)
|
||||
max_start_gap : max Abstand zwischen Starts, um zusammenzufassen
|
||||
max_end_gap : max Abstand zwischen Ends, um zusammenzufassen
|
||||
|
||||
Returns:
|
||||
merged list of (start, end)
|
||||
"""
|
||||
if not segments:
|
||||
return []
|
||||
|
||||
# Sortiere nach Start
|
||||
segments = sorted(segments, key=lambda x: x[0])
|
||||
|
||||
merged = []
|
||||
current_start, current_end = segments[0]
|
||||
|
||||
for start, end in segments[1:]:
|
||||
# Prüfen, ob sowohl Start als auch End nah genug sind
|
||||
if start - current_start <= max_start_gap and abs(end - current_end) <= max_end_gap:
|
||||
# Segment gehört zum Cluster
|
||||
current_end = max(current_end, end)
|
||||
else:
|
||||
merged.append((current_start, current_end))
|
||||
current_start, current_end = start, end
|
||||
|
||||
merged.append((current_start, current_end))
|
||||
return merged
|
||||
|
||||
|
||||
def laenge_laengstes_array(arrays):
|
||||
"""
|
||||
Gibt die Länge des längsten Arrays in einem Array von Arrays zurück.
|
||||
|
||||
Parameters:
|
||||
arrays (list of list or ndarray): Liste von Arrays
|
||||
|
||||
Returns:
|
||||
int: Länge des längsten Arrays
|
||||
"""
|
||||
# Konvertiere in ein NumPy-Array, um die Länge der inneren Arrays zu messen
|
||||
laengen = np.array([len(a) for a in arrays])
|
||||
return np.max(laengen)
|
||||
103
mdt.py
Normal file
@@ -0,0 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Thu Feb 15 10:36:14 2018
|
||||
|
||||
@author: Hauke Brunken
|
||||
"""
|
||||
|
||||
|
||||
import numpy as np
|
||||
import math
|
||||
from scipy.fftpack import fft
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.animation import FuncAnimation
|
||||
sd_found = False
|
||||
try:
|
||||
import sounddevice as sd
|
||||
sd_found = True
|
||||
except:
|
||||
print('Das Modul "sounddevice" fehlt. Es lässt sich per "pip install sounddevice" im "Anaconda Prompt" installieren.')
|
||||
|
||||
def playSound(sound, fs):
|
||||
sd.play(sound/10, fs)
|
||||
|
||||
def spectrum(Messwerte, Abtastrate):
|
||||
N=len(Messwerte)
|
||||
u_cmplx=fft(Messwerte)
|
||||
u_abs=np.abs(u_cmplx[0:N//2])/N
|
||||
u_abs[1:] *= 2
|
||||
f=np.linspace(0,Abtastrate//2,N//2)
|
||||
return (f,u_abs)
|
||||
|
||||
def dataRead(**kwargs):
|
||||
argListMust = {'amplitude', 'samplingRate', 'duration', 'channels', 'resolution', 'outType'}
|
||||
argList = {'amplitude', 'samplingRate', 'duration', 'channels', 'resolution', 'outType', 'continues'}
|
||||
for key in kwargs:
|
||||
if key not in argList:
|
||||
print('Folgende Argumente müssen übergeben werden: amplitude=[V], samplingRate=[Hz], duration=[s], channels=[[,]], resolution=[bits], outType=\'volt\' oder \'codes\')')
|
||||
return None
|
||||
for key in argListMust:
|
||||
if key not in kwargs:
|
||||
print('Folgende Argumente müssen übergeben werden: amplitude=[V], samplingRate=[Hz], duration=[s], channels=[[,]], resolution=[bits], outType=\'volt\' oder \'codes\')')
|
||||
return None
|
||||
amplitude = kwargs['amplitude']
|
||||
samplingRate = kwargs['samplingRate']
|
||||
duration = kwargs['duration']
|
||||
channels = kwargs['channels']
|
||||
resolution = kwargs['resolution']
|
||||
outType = kwargs['outType']
|
||||
if 'continues' not in kwargs.keys():
|
||||
continues = False
|
||||
else:
|
||||
continues = kwargs['continues']
|
||||
if type(continues) != bool:
|
||||
print('continues muss vom Typ bool sein')
|
||||
return None
|
||||
if not all(i < 4 for i in channels):
|
||||
print('Mögliche Kanäle sind 0 bis 4')
|
||||
return None
|
||||
if len(channels) > len(set(channels)):
|
||||
print('Kanäle dürfen nicht doppelt auftauchen')
|
||||
return None
|
||||
|
||||
|
||||
outtType = outType.capitalize()
|
||||
if outtType != 'Volt' and outtType != 'Codes':
|
||||
print(outtType)
|
||||
print('outType = \'Volt\' oder \'Codes\'')
|
||||
return None
|
||||
|
||||
u_lsb = 2*amplitude/(2**resolution-1)
|
||||
bins = [-amplitude+u_lsb/2+u_lsb*i for i in range(2**resolution-1)]
|
||||
|
||||
|
||||
ai_voltage_rngs = [1,2,5,10]
|
||||
if amplitude not in ai_voltage_rngs:
|
||||
print('Unterstützt werden folgende Amplituden:')
|
||||
print(ai_voltage_rngs)
|
||||
return None
|
||||
|
||||
for channel in channels:
|
||||
if resolution < 1 or resolution > 14:
|
||||
print(f'Die Auflösung muss zwischen 1 und 14 Bit liegen')
|
||||
return None
|
||||
|
||||
if samplingRate > 48000:
|
||||
print(f'Mit dieser Kanalanzahl beträgt die höchste Abtastrate 48000 Hz:')
|
||||
return None
|
||||
|
||||
|
||||
if continues:
|
||||
print('Die Liveansicht ist nicht verfügbar.')
|
||||
else:
|
||||
t = np.arange(0,duration,1/samplingRate)
|
||||
data = np.zeros( (len(channels),t.size))
|
||||
data[0,:] = 2.5*np.sin(2*np.pi*50*t+np.random.rand()*np.pi*2)
|
||||
data[data>amplitude] = amplitude
|
||||
data[data<-amplitude] = -amplitude
|
||||
data = np.digitize(data,bins)
|
||||
if outtType == 'Volt':
|
||||
data = data*u_lsb-amplitude
|
||||
print(f"Die Messung wurde durchgeführt mit einer virtuellen Messkarte \n Messbereich: +/-{amplitude:1.2f} Volt\n samplingRate: {samplingRate:1.1f} Hz\n Messdauer: {duration:1.3f} s\n Auflösung: {resolution:d} bit\n Ausgabe in: {outtType:s}")
|
||||
|
||||
return data
|
||||
402
plot_lib.py
Normal file
@@ -0,0 +1,402 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
|
||||
def plot_xy(x, y, xlabel="x", ylabel="y", title="Plot of y over x"):
|
||||
"""
|
||||
Plots y over x using matplotlib with:
|
||||
- X limits set exactly to the first and last x values
|
||||
- Y limits padded by ±10% of the data range
|
||||
- Custom x/y labels and title
|
||||
"""
|
||||
if len(x) == 0 or len(y) == 0:
|
||||
raise ValueError("x and y must not be empty")
|
||||
if len(x) != len(y):
|
||||
raise ValueError("x and y must have the same length")
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
plt.plot(x, y)
|
||||
|
||||
# Set x-axis exactly to first and last value
|
||||
plt.xlim(x[0], x[-1])
|
||||
|
||||
# Compute y padding
|
||||
ymin, ymax = min(y), max(y)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1 # avoid zero-range issue
|
||||
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# Labels and title
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.title(title)
|
||||
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
def plot_xy_points(x, y, xlabel="x", ylabel="y", title="Plot of y over x"):
|
||||
"""
|
||||
Plots y over x using matplotlib with:
|
||||
- A line plot + dots on each measurement point
|
||||
- X limits set exactly to the first and last x values
|
||||
- Y limits padded by ±10% of the data range
|
||||
- Custom x/y labels and title
|
||||
"""
|
||||
if len(x) == 0 or len(y) == 0:
|
||||
raise ValueError("x and y must not be empty")
|
||||
if len(x) != len(y):
|
||||
raise ValueError("x and y must have the same length")
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
|
||||
# Plot line
|
||||
plt.plot(x, y)
|
||||
|
||||
# Plot dots at measurement values
|
||||
plt.scatter(x, y)
|
||||
|
||||
# Set x limits exactly to first and last value
|
||||
plt.xlim(x[0], x[-1])
|
||||
|
||||
# Compute y padding
|
||||
ymin, ymax = min(y), max(y)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1 # avoid zero-range issue
|
||||
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# Labels and title
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.title(title)
|
||||
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
def plot_mult_xy(x_list, y_list, legends, xlabel="x", ylabel="y", title="Plot"):
|
||||
"""
|
||||
Plots multiple y-over-x curves using matplotlib.
|
||||
|
||||
Parameters:
|
||||
x_list : list of x arrays
|
||||
y_list : list of y arrays
|
||||
legends : list of legend labels
|
||||
xlabel : x axis label
|
||||
ylabel : y axis label
|
||||
title : plot title
|
||||
"""
|
||||
|
||||
if len(x_list) != len(y_list):
|
||||
raise ValueError("x_list and y_list must have the same number of elements")
|
||||
if len(legends) != len(x_list):
|
||||
raise ValueError("Number of legends must match number of curves")
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
|
||||
# Track global y range
|
||||
all_y = []
|
||||
|
||||
for x, y, label in zip(x_list, y_list, legends):
|
||||
if len(x) != len(y):
|
||||
raise ValueError(f"Length mismatch in dataset '{label}'")
|
||||
|
||||
plt.plot(x, y, label=label)
|
||||
all_y.extend(y)
|
||||
|
||||
# Global y-axis padding
|
||||
ymin, ymax = min(all_y), max(all_y)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# Global x-axis: from smallest first x to largest last x
|
||||
x_start = min(x[0] for x in x_list)
|
||||
x_end = max(x[-1] for x in x_list)
|
||||
plt.xlim(x_start, x_end)
|
||||
|
||||
# Labels, grid, legend
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.title(title)
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
def plot_mult_xy_points(x_list, y_list, legends, xlabel="x", ylabel="y", title="Plot"):
|
||||
"""
|
||||
Same as plot_xy, but also places dots at each measured point.
|
||||
"""
|
||||
|
||||
if len(x_list) != len(y_list):
|
||||
raise ValueError("x_list and y_list must have the same number of elements")
|
||||
if len(legends) != len(x_list):
|
||||
raise ValueError("Number of legends must match number of curves")
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
|
||||
all_y = []
|
||||
|
||||
for x, y, label in zip(x_list, y_list, legends):
|
||||
if len(x) != len(y):
|
||||
raise ValueError(f"Length mismatch in dataset '{label}'")
|
||||
|
||||
# Line + dots
|
||||
plt.plot(x, y, label=label)
|
||||
plt.scatter(x, y)
|
||||
|
||||
all_y.extend(y)
|
||||
|
||||
# Y-axis padding
|
||||
ymin, ymax = min(all_y), max(all_y)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# X-axis range
|
||||
x_start = min(x[0] for x in x_list)
|
||||
x_end = max(x[-1] for x in x_list)
|
||||
plt.xlim(x_start, x_end)
|
||||
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.title(title)
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_shared_xy(
|
||||
x,
|
||||
y_list,
|
||||
labels=None,
|
||||
xlabel="X",
|
||||
ylabel="Y",
|
||||
title="Plot",
|
||||
show_points=False,
|
||||
figsize=(10,6),
|
||||
linewidth=2,
|
||||
marker_size=60,
|
||||
log_x=False,
|
||||
log_y=False,
|
||||
save_path=None # <-- NEW
|
||||
):
|
||||
"""
|
||||
Plot multiple y-arrays over the same x-array using shared axes.
|
||||
Supports optional logarithmic axes, padding, and SVG saving.
|
||||
"""
|
||||
|
||||
x = np.asarray(x)
|
||||
|
||||
# Validate y lengths
|
||||
for idx, y in enumerate(y_list):
|
||||
if len(y) != len(x):
|
||||
raise ValueError(f"y_list[{idx}] does not match length of x")
|
||||
|
||||
plt.figure(figsize=figsize)
|
||||
|
||||
# Plot each curve
|
||||
for idx, y in enumerate(y_list):
|
||||
y = np.asarray(y)
|
||||
label = labels[idx] if labels else None
|
||||
plt.plot(x, y, linewidth=linewidth, label=label)
|
||||
if show_points:
|
||||
plt.scatter(x, y, s=marker_size)
|
||||
|
||||
# X-axis range
|
||||
plt.xlim(x[0], x[-1])
|
||||
|
||||
# Y-axis padding
|
||||
all_y = np.concatenate([np.asarray(y) for y in y_list])
|
||||
ymin, ymax = np.min(all_y), np.max(all_y)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# Axis labels
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
|
||||
# Optional log scaling
|
||||
if log_x:
|
||||
plt.xscale("log")
|
||||
if log_y:
|
||||
plt.yscale("log")
|
||||
|
||||
# Title / legend / grid
|
||||
plt.title(title)
|
||||
if labels:
|
||||
plt.legend()
|
||||
plt.grid(True, which="both")
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
# === SVG Saving Logic ===============================
|
||||
if save_path is not None and str(save_path).strip() != "":
|
||||
save_path = str(save_path)
|
||||
|
||||
# Ensure .svg extension
|
||||
if not save_path.lower().endswith(".svg"):
|
||||
save_path += ".svg"
|
||||
|
||||
# If file exists, ask for overwrite or rename
|
||||
if os.path.exists(save_path):
|
||||
print(f"File '{save_path}' already exists.")
|
||||
choice = input("Overwrite? (y/n): ").strip().lower()
|
||||
|
||||
if choice != "y":
|
||||
new_path = input("Enter new filename (with or without .svg): ").strip()
|
||||
if not new_path.lower().endswith(".svg"):
|
||||
new_path += ".svg"
|
||||
save_path = new_path
|
||||
|
||||
# Save the file now
|
||||
plt.savefig(save_path, format="svg")
|
||||
print(f"Saved SVG to: {save_path}")
|
||||
# =====================================================
|
||||
|
||||
plt.show()
|
||||
|
||||
def plot_difference(
|
||||
x,
|
||||
y1,
|
||||
y2,
|
||||
absolute=False,
|
||||
return_sum=False, # Return sum instead of array
|
||||
xlabel="X",
|
||||
ylabel="Difference",
|
||||
title="Difference Plot",
|
||||
show_points=False,
|
||||
figsize=(10,6),
|
||||
linewidth=2,
|
||||
marker_size=60,
|
||||
log_x=False,
|
||||
log_y=False,
|
||||
save_path=None
|
||||
):
|
||||
"""
|
||||
Plot the difference between two y-series over the same x.
|
||||
Optionally compute absolute difference and optionally return the sum
|
||||
of the difference values instead of the full array.
|
||||
|
||||
NOTE: This version intentionally provides NO LEGEND.
|
||||
"""
|
||||
|
||||
# Convert to arrays
|
||||
x = np.asarray(x)
|
||||
y1 = np.asarray(y1)
|
||||
y2 = np.asarray(y2)
|
||||
|
||||
# Validate size
|
||||
if len(y1) != len(x) or len(y2) != len(x):
|
||||
raise ValueError("y1 and y2 must match the length of x")
|
||||
|
||||
# Compute difference
|
||||
diff = y2 - y1
|
||||
if absolute:
|
||||
diff = np.abs(diff)
|
||||
|
||||
# === Plotting ===
|
||||
plt.figure(figsize=figsize)
|
||||
|
||||
plt.plot(
|
||||
x,
|
||||
diff,
|
||||
linewidth=linewidth
|
||||
)
|
||||
|
||||
if show_points:
|
||||
plt.scatter(x, diff, s=marker_size)
|
||||
|
||||
# X limits
|
||||
plt.xlim(x[0], x[-1])
|
||||
|
||||
# Y padding
|
||||
ymin, ymax = np.min(diff), np.max(diff)
|
||||
yrange = ymax - ymin
|
||||
pad = yrange * 0.10 if yrange != 0 else 1
|
||||
plt.ylim(ymin - pad, ymax + pad)
|
||||
|
||||
# Labels & styling
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.title(title)
|
||||
plt.grid(True, which="both")
|
||||
|
||||
# Apply log scales
|
||||
if log_x:
|
||||
plt.xscale("log")
|
||||
if log_y:
|
||||
plt.yscale("log")
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
# === SVG Saving Logic ===
|
||||
if save_path is not None and str(save_path).strip() != "":
|
||||
save_path = str(save_path)
|
||||
|
||||
if not save_path.lower().endswith(".svg"):
|
||||
save_path += ".svg"
|
||||
|
||||
if os.path.exists(save_path):
|
||||
print(f"File '{save_path}' already exists.")
|
||||
choice = input("Overwrite? (y/n): ").strip().lower()
|
||||
if choice != "y":
|
||||
new_path = input(
|
||||
"Enter new filename (with or without .svg): "
|
||||
).strip()
|
||||
if not new_path.lower().endswith(".svg"):
|
||||
new_path += ".svg"
|
||||
save_path = new_path
|
||||
|
||||
plt.savefig(save_path, format="svg")
|
||||
print(f"Saved SVG to: {save_path}")
|
||||
# ===========================
|
||||
|
||||
plt.show()
|
||||
|
||||
# === Return requested output ===
|
||||
if return_sum:
|
||||
return np.sum(diff)
|
||||
else:
|
||||
return diff
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
# x = [1, 2, 3, 4, 5]
|
||||
# y = [2, 3, 5, 7, 11]
|
||||
# plot_xy_points(x, y, "X-axis", "Y-axis", "Sample Plot")
|
||||
|
||||
# x1 = [0, 1, 2, 3]
|
||||
# y1 = [2, 5, 3, 6]
|
||||
|
||||
# x2 = [0, 1, 2, 3]
|
||||
# y2 = [1, 4, 2, 7]
|
||||
|
||||
# plot_mult_xy_points(
|
||||
# [x1, x2],
|
||||
# [y1, y2],
|
||||
# legends=["Sensor A", "Sensor B"],
|
||||
# xlabel="Time (s)",
|
||||
# ylabel="Value",
|
||||
# title="Line Plot"
|
||||
# )
|
||||
|
||||
|
||||
x = [0, 1, 2, 3]
|
||||
y1 = [10, 20, 18, 30]
|
||||
y2 = [12, 22, 19, 29]
|
||||
y3 = [8, 18, 17, 27]
|
||||
|
||||
plot_shared_xy(
|
||||
x=[0,1,2,3],
|
||||
y_list=[[10,20,18,30], [12,21,17,28]],
|
||||
labels=["A","B"],
|
||||
show_points=True,
|
||||
save_path="my_plot.svg"
|
||||
)
|
||||
|
||||
1348
prak1/Stromwandler-Kennlinie.svg
Normal file
|
After Width: | Height: | Size: 38 KiB |
1172
prak1/Stromwandler-Vergleich-Kennlinie.svg
Normal file
|
After Width: | Height: | Size: 33 KiB |
19200
prak2/333_output1k.txt
Normal file
19200
prak2/333_output3k.txt
Normal file
19200
prak2/333_output5k.txt
Normal file
1148
prak2/kennlinie_tiefpass.svg
Normal file
|
After Width: | Height: | Size: 35 KiB |
1219
prak2/kennlinie_tiefpass_diff.svg
Normal file
|
After Width: | Height: | Size: 37 KiB |
18
prak2/test
Normal file
@@ -0,0 +1,18 @@
|
||||
DC Tiefpass
|
||||
-10 -10.001
|
||||
-8 -8.005
|
||||
-6 -6.010
|
||||
-4 -4.015
|
||||
-2 -2.020
|
||||
0 -0.026
|
||||
2 1.963
|
||||
4 3.958
|
||||
6 5.953
|
||||
8 7.948
|
||||
10 9.942
|
||||
|
||||
|
||||
Wiedertand Timing
|
||||
1kO 260µs
|
||||
3kO 700µs
|
||||
5kO 1.2 ms
|
||||
12
prak2/test.txt
Normal file
@@ -0,0 +1,12 @@
|
||||
Voltage Voltage
|
||||
-10 -10.001
|
||||
-8 -8.005
|
||||
-6 -6.010
|
||||
-4 -4.015
|
||||
-2 -2.020
|
||||
0 -0.026
|
||||
2 1.963
|
||||
4 3.958
|
||||
6 5.953
|
||||
8 7.948
|
||||
10 9.942
|
||||
2246
prak2/tiefpass_mult_r.svg
Normal file
|
After Width: | Height: | Size: 101 KiB |
1376
prak4/3-bit-adu.svg
Normal file
|
After Width: | Height: | Size: 35 KiB |
2692
prak4/4-bit-adu-auto.svg
Normal file
|
After Width: | Height: | Size: 85 KiB |
1192
prak4/4-bit-adu-manuell.svg
Normal file
|
After Width: | Height: | Size: 32 KiB |
2099
prak4/4bit-adu-kennlinie.svg
Normal file
|
After Width: | Height: | Size: 52 KiB |
1941
prak4/ADU-Kennlinie.svg
Normal file
|
After Width: | Height: | Size: 60 KiB |
6293
prak4/aliasing_10000.svg
Normal file
|
After Width: | Height: | Size: 151 KiB |
11165
prak4/aliasing_12500.svg
Normal file
|
After Width: | Height: | Size: 266 KiB |
9193
prak4/aliasing_15000.svg
Normal file
|
After Width: | Height: | Size: 220 KiB |
10483
prak4/aliasing_17500.svg
Normal file
|
After Width: | Height: | Size: 250 KiB |
8092
prak4/aliasing_20000.svg
Normal file
|
After Width: | Height: | Size: 194 KiB |
11793
prak4/aliasing_25000.svg
Normal file
|
After Width: | Height: | Size: 282 KiB |
9676
prak4/aliasing_30000.svg
Normal file
|
After Width: | Height: | Size: 232 KiB |
13617
prak4/aliasing_35000.svg
Normal file
|
After Width: | Height: | Size: 324 KiB |
11444
prak4/aliasing_40000.svg
Normal file
|
After Width: | Height: | Size: 274 KiB |
1439
prak4/aliasing_mit_filter_10000.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1679
prak4/aliasing_mit_filter_44000.svg
Normal file
|
After Width: | Height: | Size: 42 KiB |
2771
prak4/aliasing_ohne_filter_10000.svg
Normal file
|
After Width: | Height: | Size: 69 KiB |
3710
prak4/aliasing_ohne_filter_44000.svg
Normal file
|
After Width: | Height: | Size: 92 KiB |
1509
prak4/prak4/4-bit-adu-theorie.svg
Normal file
|
After Width: | Height: | Size: 42 KiB |
80000
prak4/prak4/ADU-Kennlinie_automatisch.csv
Executable file
6
prak4/prak4/ADU-Kennlinie_manuell.csv
Normal file
@@ -0,0 +1,6 @@
|
||||
Von,Bis,Code
|
||||
-5,-4.67,000
|
||||
-4.67,-4.0,001
|
||||
-4.0,-3.33,010
|
||||
-3.33,-2.67,011
|
||||
-2.67,-2,100
|
||||
|
10000
prak4/prak4/Aliasing_10000.csv
Executable file
12500
prak4/prak4/Aliasing_12500.csv
Executable file
15000
prak4/prak4/Aliasing_15000.csv
Executable file
17500
prak4/prak4/Aliasing_17500.csv
Executable file
20000
prak4/prak4/Aliasing_20000.csv
Executable file
25000
prak4/prak4/Aliasing_25000.csv
Executable file
30000
prak4/prak4/Aliasing_30000.csv
Executable file
35000
prak4/prak4/Aliasing_35000.csv
Executable file
40000
prak4/prak4/Aliasing_40000.csv
Executable file
10000
prak4/prak4/Aliasingfilter_mit_box_10000.csv
Executable file
44000
prak4/prak4/Aliasingfilter_mit_box_44000.csv
Executable file
10000
prak4/prak4/Aliasingfilter_ohne_box_10000.csv
Executable file
44000
prak4/prak4/Aliasingfilter_ohne_box_44000.csv
Executable file
40000
prak4/prak4/Quantisierungsrauschen.csv
Executable file
51
prak4/read.py
Executable file
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Thu Feb 15 17:59:51 2018
|
||||
|
||||
@author: Hauke Brunken
|
||||
"""
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
plt.close()
|
||||
import numpy as np
|
||||
import mdt
|
||||
|
||||
file = r"C:\Users\Student\Desktop\Neuer Ordner\Aliasingfilter_mit_box"
|
||||
|
||||
rates=[10000,44000]
|
||||
for rate in rates:
|
||||
data = mdt.dataRead(amplitude = 10, samplingRate = rate, duration = 1, channels = [0], resolution = 14, outType = 'Volt', continues=False )
|
||||
f,u = mdt.spectrum(data, rate)
|
||||
fig, (ax1,ax2) = plt.subplots(2)
|
||||
ax1.plot(data)
|
||||
ax2.plot(f,u)
|
||||
Title= "Alialising Rechtecksignal Filtered" +str(rate/1000) +"kHz"
|
||||
file_name = f"{file}_{rate}.csv"
|
||||
with open(file_name, 'w') as f:
|
||||
np.savetxt(f, data, delimiter=',')
|
||||
# np.save(Title, data)
|
||||
#plt.savefig('Alialasing' + strate + "Hz.pdf")
|
||||
|
||||
#file = r"C:\Users\Student\Desktop\Neuer Ordner\Aliasing"
|
||||
|
||||
#rates = [40000, 35000, 30000, 25000, 20000, 17500, 15000, 12500, 10000]
|
||||
|
||||
|
||||
#for i in range(len(rates)):
|
||||
# data = mdt.dataRead(amplitude=10, samplingRate=rates[i], duration=1, channels=[0], resolution=14, outType='Volt')
|
||||
# file_name = f"{file}_{rates[i]}.csv"
|
||||
# with open(file_name, 'w') as f:
|
||||
# np.savetxt(f, data, delimiter=',')
|
||||
#data = mdt.dataRead(amplitude=10, samplingRate=rates[len(rates)-1], duration=1, channels=[0], resolution=14, outType='Volt')
|
||||
#plt.plot(data, marker='x')
|
||||
#plt.show()
|
||||
|
||||
#plt.tight_layout()
|
||||
#plt.show()
|
||||
#np.save("ADUKennlinie Sinussignal", data)
|
||||
#data = np.load("TP_5kOhm.npy")
|
||||
#plt.plot(data[0])
|
||||
#plt.plot(data[1])
|
||||
|
||||
|
||||
# hey ihr! holt euch euren eigenen code!
|
||||
1968
prak4/sin_all.svg
Normal file
|
After Width: | Height: | Size: 55 KiB |
2006
prak4/sin_diff.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
2022
prak4/sin_normal.svg
Normal file
|
After Width: | Height: | Size: 51 KiB |
BIN
prak5/5.4.1_LED.npy
Executable file
BIN
prak5/5.4.1_Leuchtstoffroehre.npy
Executable file
BIN
prak5/5.4.1_glueh.npy
Executable file
24
prak5/Messung5.py
Executable file
@@ -0,0 +1,24 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import mdt
|
||||
|
||||
|
||||
data = mdt.dataRead(amplitude = 10, samplingRate = 24000, duration =2, channels = [0,1], resolution = 14, outType = 'Volt',
|
||||
continues = False)
|
||||
|
||||
plt.plot(data[0], label='Spannung')
|
||||
plt.plot(data[1], label='Strom')
|
||||
|
||||
print(data)
|
||||
|
||||
plt.legend()
|
||||
|
||||
|
||||
# 5.4.1
|
||||
# np.save('5.4.1_glueh.npy', data)
|
||||
# np.save('5.4.1_LED.npy', data)
|
||||
# np.save('5.4.1_Leuchtstoffroehre.npy', data)
|
||||
|
||||
|
||||
# 5.4.3
|
||||
# np.save('5.4.3_Leuchtstoffroehre.npy', data)
|
||||
BIN
prak5/aufgabe_5,4,3glüh.npy
Executable file
1809
prak5/dimmer.svg
Normal file
|
After Width: | Height: | Size: 59 KiB |
1332
prak5/dimmer_mesung.svg
Normal file
|
After Width: | Height: | Size: 40 KiB |
1450
prak5/dimmer_theorie.svg
Normal file
|
After Width: | Height: | Size: 39 KiB |
1391
prak5/glühbirne_verlauf.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1491
prak5/leuchtröhre_verlauf.svg
Normal file
|
After Width: | Height: | Size: 39 KiB |
67
prak5/test2.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import numpy as np
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
def generate_sin_wave(frequency, amplitude, duration, phase_shift=0):
|
||||
"""
|
||||
Generate a sine wave with specified parameters.
|
||||
|
||||
Parameters:
|
||||
frequency (float): Frequency of the sine wave in Hz
|
||||
amplitude (float): Amplitude of the sine wave
|
||||
duration (float): Duration of the sine wave in seconds (can be fractional)
|
||||
phase_shift (float): Phase shift in radians (default: 0)
|
||||
|
||||
Returns:
|
||||
tuple: (time_array, sine_wave_array)
|
||||
"""
|
||||
# Generate time array with fractional seconds support
|
||||
sample_rate = 44100 # Standard audio sample rate
|
||||
num_samples = int(duration * sample_rate)
|
||||
t = np.linspace(0, duration, num_samples)
|
||||
|
||||
# Generate sine wave with phase shift
|
||||
y = amplitude * np.sin(2 * np.pi * frequency * t + phase_shift)
|
||||
|
||||
return t, y
|
||||
|
||||
|
||||
t, v = generate_sin_wave(60, 325, 0.045, 0)
|
||||
t2, i = generate_sin_wave(60, 0.125, 0.045, 45)
|
||||
|
||||
w = np.multiply(v,i)
|
||||
V = np.divide(230, np.sqrt(2))
|
||||
I = np.divide(0.125, np.sqrt(2))
|
||||
P = np.multiply(np.multiply(V,I), np.cos(np.deg2rad(45)))
|
||||
q = np.multiply(np.multiply(V,I), np.sin(np.deg2rad(45)))
|
||||
s = np.sqrt(np.square(P) + np.square(q))
|
||||
|
||||
S = []
|
||||
for _ in range(len(t)):
|
||||
S.append(s)
|
||||
Q = []
|
||||
for _ in range(len(t)):
|
||||
Q.append(q)
|
||||
|
||||
|
||||
|
||||
# plot a graph with i, v and w over t
|
||||
plt.plot(np.multiply(t, 1000), v, label='voltage in V')
|
||||
plt.plot(np.multiply(t2, 1000), np.multiply(i, 1000), label='current in mA')
|
||||
plt.plot(np.multiply(t, 1000), w, label='Leistung in W')
|
||||
# plt.plot(np.multiply(t, 1000), P, label='Wirkleistung in W')
|
||||
plt.plot(np.multiply(t, 1000), Q, label='Blindleistung in W')
|
||||
# plt.plot(np.multiply(t, 1000), S, label='Scheinleistung in W')
|
||||
plt.legend()
|
||||
plt.grid()
|
||||
plt.xlabel('time in ms')
|
||||
plt.ylabel('value')
|
||||
|
||||
#save plot as svg
|
||||
# plt.savefig('prak5/glühbirne_verlauf.svg', format='svg')
|
||||
plt.savefig('prak5/leuchtröhre_verlauf.svg', format='svg')
|
||||
|
||||
plt.show()
|
||||
|
||||
0x7ffbfe8
|
||||
|
||||
0x7ffbff4
|
||||
44
read_file.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import numpy as np
|
||||
|
||||
def read_xy_file(path):
|
||||
"""
|
||||
Reads a 2-column text file and returns x and y arrays.
|
||||
Assumes the first line is a header.
|
||||
"""
|
||||
x_vals = []
|
||||
y_vals = []
|
||||
|
||||
with open(path, "r") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
# Skip header (line 0)
|
||||
for line in lines[1:]:
|
||||
if not line.strip():
|
||||
continue # skip empty lines
|
||||
parts = line.split()
|
||||
if len(parts) < 2:
|
||||
continue # skip malformed lines
|
||||
|
||||
x_vals.append(float(parts[0]))
|
||||
y_vals.append(float(parts[1]))
|
||||
|
||||
return x_vals, y_vals
|
||||
|
||||
def read_data_with_indices(filename):
|
||||
"""
|
||||
Reads a file with one float per line and returns two arrays:
|
||||
- data_array: the floats from the file
|
||||
- index_array: the corresponding indices
|
||||
"""
|
||||
# Read the data into a numpy array
|
||||
data_array = np.loadtxt(filename, dtype=float)
|
||||
|
||||
# Generate an array of indices
|
||||
index_array = np.arange(len(data_array))
|
||||
|
||||
return data_array, index_array
|
||||
|
||||
if __name__ == "__main__":
|
||||
x, y = read_xy_file("prak2/test.txt")
|
||||
print(x)
|
||||
print(y)
|
||||