fit.py: Update to improve syntax

This commit is contained in:
2025-05-26 17:16:31 +02:00
parent 096003ffa9
commit f560c24574

View File

@@ -1,36 +1,29 @@
import csv import csv
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
go = 0
n = int(input("Aktuelle Sondennummer: ")) n = int(input("Sensor number to be printed: "))
try: file = ""
imp = open("Sonden2021.csv", "r")
go = 1
except FileNotFoundError:
print("Failed to open file (non-existent or corrupted?)")
go = 0
if go == 1: def generate_plot():
reader = csv.reader(imp, delimiter=',') reader = csv.reader(file, delimiter=',')
rohdaten = list(reader) data = list(reader)
rohdaten.sort(key=lambda imp: float(imp[2])) data.sort(key=lambda imp: float(imp[2]))
lenght = len(rohdaten) lenght = len(data)
x = [] x = []
y = [] y = []
for i in range(lenght): for _ in range(lenght):
extract = rohdaten.pop(0) extract = data.pop(0)
sondennummer = int(extract.pop(0)) sensor = int(extract.pop(0))
if sondennummer == n: if sensor == n:
ye = extract.pop(0) ye = extract.pop(0)
xe = extract.pop(0) xe = extract.pop(0)
y.append(float(ye)) y.append(float(ye))
x.append(float(xe)) x.append(float(xe))
fit = np.polyfit(x, y, 2) fit = np.polyfit(x, y, 2)
print(fit)
formula = f"F(U) = {round(float(fit[0]), 4)}U^2+{round(float(fit[1]), 4)}U+{round(float(fit[2]), 4)}" formula = f"F(U) = {round(float(fit[0]), 4)}U^2+{round(float(fit[1]), 4)}U+{round(float(fit[2]), 4)}"
@@ -38,24 +31,30 @@ if go == 1:
plt.plot(x, fit_fn(x), color="BLUE", label="T(U)") plt.plot(x, fit_fn(x), color="BLUE", label="T(U)")
plt.scatter(x, y, color="MAGENTA", marker="o", label="Messsdaten") plt.scatter(x, y, color="MAGENTA", marker="o", label="Data")
plt.ylabel("Temperatur") plt.ylabel("Temperature")
plt.xlabel("Spannung") plt.xlabel("Voltage")
titel = 'Temperatursonde MCP9701A Nummer: {}'.format(n) title = 'Sensor MCP9701A #{}'.format(n)
plt.title(titel) plt.title(title)
plt.axis([0.6, 2, 15, 70]) plt.axis((0.6, 2.0, 15.0, 70.0))
plt.legend(loc="lower right") plt.legend(loc="lower right")
plt.annotate(formula, xy=(0.85, 60)) plt.annotate(formula, xy=(0.85, 60))
plt.grid(True) plt.grid(True)
plt.show() plt.show()
saveit = input("Soll der Graph gespeichert werden? (y/n) ").lower() saveit = input("Do you wish to save the plot? (y/N) ").lower()
if saveit == "y": if saveit == "y":
plt.savefig("Sonde"+str(n)+".png") plt.savefig("Sensor"+str(n)+".png")
plt.savefig("Sonde"+str(n)+".pdf", format="pdf") plt.savefig("Sensor"+str(n)+".pdf", format="pdf")
plt.savefig("Sonde"+str(n)+".svg", format="svg") plt.savefig("Sensor"+str(n)+".svg", format="svg")
print("saved images") print("==> Images saved")
else: else:
print("discarded images") print("==> Images discarded")
filename = input("Please enter a file path to the csv file to be plotted: ")
try:
file = open(filename, "r")
generate_plot()
except FileNotFoundError:
print("Failed to open file (non-existent or corrupted?)")