optimized code in fit.py

This commit is contained in:
janis
2022-06-29 17:50:35 +02:00
parent de84292bb8
commit d15fa5dd45

View File

@@ -1,16 +1,24 @@
import csv import csv
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
n = int(input("Aktuelle Sondennummer: ")) go = 0
imp = open("Sonden2021.csv", "r") n = int(input("Aktuelle Sondennummer: "))
reader = csv.reader(imp, delimiter=',') try:
rohdaten = list(reader) imp = open("Sonden2021.csv", "r")
rohdaten.sort(key=lambda imp: float(imp[2])) go = 1
lenght = len(rohdaten) except FileNotFoundError:
x = [] print("Failed to open file (non-existent or corrupted")
y = [] go = 0
for i in range(lenght): if go == 1:
reader = csv.reader(imp, delimiter=',')
rohdaten = list(reader)
rohdaten.sort(key=lambda imp: float(imp[2]))
lenght = len(rohdaten)
x = []
y = []
for i in range(lenght):
extract = rohdaten.pop(0) extract = rohdaten.pop(0)
sondennummer = int(extract.pop(0)) sondennummer = int(extract.pop(0))
if sondennummer == n: if sondennummer == n:
@@ -19,33 +27,34 @@ for i in range(lenght):
y.append(float(xe)) y.append(float(xe))
x.append(float(ye)) x.append(float(ye))
fit = np.polyfit(x,y,2) fit = np.polyfit(x, y, 2)
print(fit) print(fit)
formula = "F(U) = %sU^2+%sU+%s"%(str(round(float(fit[0]),4)),str(round(float(fit[1]),4)),str(round(float(fit[2]),4))) formula = "F(U) = %sU^2+%sU+%s"%(str(), str(round(float(fit[1]), 4)), str(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)}"
fit_fn = np.poly1d(fit) fit_fn = np.poly1d(fit)
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="Messsdaten")
plt.ylabel("Temperatur") plt.ylabel("Temperatur")
plt.xlabel("Spannung") plt.xlabel("Spannung")
titel = 'Temperatursonde MCP9701A Nummer: {}'.format(n) titel = 'Temperatursonde MCP9701A Nummer: {}'.format(n)
plt.title(titel) plt.title(titel)
plt.axis([0.6, 2, 15, 70]) plt.axis([0.6, 2, 15, 70])
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("Sollen der Graph gespeichert werden? (y/n) ").lower() saveit = input("Soll der Graph gespeichert werden? (y/n) ").lower()
if saveit == "y": if saveit == "y":
plt.savefig("Sonde"+str(n)+".png") plt.savefig("Sonde"+str(n)+".png")
plt.savefig("Sonde"+str(n)+".pdf", format="pdf") plt.savefig("Sonde"+str(n)+".pdf", format="pdf")
plt.savefig("Sonde"+str(n)+".svg", format="svg") plt.savefig("Sonde"+str(n)+".svg", format="svg")
print("saved images") print("saved images")
else: else:
print("discarded images") print("discarded images")