import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import serial import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from tkinter import * from sklearn.linear_model import LinearRegression from matplotlib import style from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import pandas as pd #import plottools from functools import partial import time import math import os import threading from threading import Thread import sys import random from Fluigent.SDK import fgt_init, fgt_close from Fluigent.SDK import fgt_set_pressure, fgt_get_pressure, fgt_get_pressureRange import csv from FireControl import FireSting3 import multiprocessing from openpyxl import Workbook ############################ connection to firesting ############################### firestingconnect = False O2datarray = [0, 0, 0, 0] O2saving = pd.DataFrame(columns=["sensor 1", "sensor 2", "sensor 3", "sensor 4", "time elapsed (s)"]) writeo2data = False def connecttofiresting(): global firestingconnect, firesting firesting=FireSting3.FireSting('COM4') firesting.channels[1].temperature = 37 firesting.channels[2].temperature = 37 firesting.channels[3].temperature = 37 firesting.channels[4].temperature = 37 print(firesting.measure()) prueba=firesting.measure() firestingconnect = True thread1 = threading.Thread(target=o2iteration) thread1.start() ############################# conexion to arduino #####################\ writedata=False arduinoconnect = False dataArray = [0, 0, 0, 0] savevalues = pd.DataFrame(columns=["sensor 1", "sensor 2", "sensor 3", "sensor 4", "time elapsed (s)"]) def connecttoarduino(): global ser, arduinoconnect ser = serial.Serial("COM5", 9600) ser_bytes = ser.readline() arduinoconnect = True thread1 = threading.Thread(target=readingarduino) thread1.start() ################################Generalities of Graph####################################### leng = 201 minvalue=8700 maxvalue=9500 today=pd.Timestamp("today").strftime("%m/%d/%Y/%H/%M/%S") todayfixed=today.replace('/','_') offset = [0, 0, 0, 0] offset1 = 0 offset2 = 0 offset3 = 0 offset4 = 0 fig = plt.figure(figsize=(14, 8.5)) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) fig2 = plt.figure(figsize=(14, 8.5)) ax5 = fig2.add_subplot(2, 2, 1) ax6 = fig2.add_subplot(2, 2, 2) ax7 = fig2.add_subplot(2, 2, 3) ax8 = fig2.add_subplot(2, 2, 4) graphX, = ax1.plot([], [], 'b', label='sensor 1') graphY, = ax2.plot([], [], 'r', label='sensor 2') graphZ, = ax3.plot([], [], 'g', label='sensor 3') graphD, = ax4.plot([], [], 'y', label = 'sensor 4') graphO21, = ax5.plot([], [], 'b', linestyle='dashdot', label = 'O2 sensor') graphO22, = ax6.plot([], [], 'r', linestyle='dashdot', label = 'O2 sensor') graphO23, = ax7.plot([], [], 'g', linestyle='dashdot', label = 'O2 sensor') graphO24, = ax8.plot([], [], 'y', linestyle='dashdot', label = 'O2 sensor') axes = [ax1, ax2, ax3, ax4] gato = [ax5, ax6, ax7, ax8] for ax in axes: ax.set_xlim(0, leng - 1) ax.set_ylim(minvalue, maxvalue) ax.set_ylabel('mechanical load') ax.set_xlabel('measure points (0.1 seconds)') ax.grid(True) for ax in gato: ax.set_xlim(0, leng - 1) ax.set_ylim(-10, 20) ax.set_ylabel('O2 %') ax.set_xlabel('measure points (0.1 seconds)') ax.grid(True) ax.legend(loc='upper right', shadow=True, ncol=1) t = list(range(0, leng)) accX = [] accY = [] accZ = [] accD = [] accO21= [] accO22= [] accO23= [] accO24= [] for i in range(0, leng): accX.append(0) accY.append(0) accZ.append(0) accD.append(0) accO21.append(0) accO22.append(0) accO23.append(0) accO24.append(0) def init(): graphX.set_data([], []) graphY.set_data([], []) graphZ.set_data([], []) graphD.set_data([], []) graphO21.set_data([], []) graphO22.set_data([], []) graphO23.set_data([], []) graphO23.set_data([], []) return graphX, graphY, graphZ, graphD #graphO21, graphO22, graphO23, graphO24 ##########################mechanical load simple + multiple######################## def paralsinglemechload(sensorindex,sleepy,pressure): sleepy = float(sleepy.get()) pressure= float(pressure.get()) print(sleepy, pressure) fgt_set_pressure(sensorindex, 0) x = threading.Thread(target=singlemechload, args=(sensorindex, sleepy, pressure)) x.start() def paralmultimechload(sensorindex, sleepy1, sleepy2, sleepy3, lenght1, length2, length3, pressure1, pressure2, pressure3): sleepy1 = float(sleepy1.get()) #sleepy2 = float(sleepy2.get()) #sleepy3 = float(sleepy3.get()) #length1 = float(length1.get()) #length2 = float(length2.get()) #length3 = float(length3.get()) #pressure1= float(pressure1.get()) #pressure2 = float(pressure2.get()) #pressure3 = float(pressure3.get()) fgt_set_pressure(sensorindex, 0) x = threading.Thread(target=multimechload, args=(sensorindex, sleepy1, sleepy2, sleepy3, lenght1, length2, length3, pressure1, pressure2, pressure3)) x.start() def singlemechload(sensorindex,sleepy,pressure): global timer, pressureMeasurement, save1, now, waiting_time, oxygenX while True: fgt_set_pressure(sensorindex, pressure) time.sleep(sleepy) fgt_set_pressure(sensorindex, 0) print("yay" + str(sensorindex)) if stop[sensorindex] == True: pass def multimechload(sensorindex, sleepy1, sleepy2, sleepy3, lenght1, length2, length3, pressure1, pressure2, pressure3): start = time.time() sleepy1 = 1/sleepy1 sleepy2 = 1/sleepy2 sleepy3 = 1/sleepy3 while True: end = time.time() - start if end <= lenght1: fgt_set_pressure(sensorindex, pressure1 ) time.sleep(sleepy1) fgt_set_pressure(sensorindex, 0) elif end >= lenght1 or end <= length2: fgt_set_pressure(sensorindex, pressure2) time.sleep(sleepy2) fgt_set_pressure(sensorindex, 0) elif end >= lenght2 or end <= length3: fgt_set_pressure(sensorindex, pressure2) time.sleep(sleepy2) fgt_set_pressure(sensorindex, 0) else: pass ############################O2 PID######################## def paralsimpleo2control(i, o2channel, objective, tolerance, action): #print(objective) objective = objective.get() Tolerance = tolerance.get() action = action.get() fgt_set_pressure(o2channel, 0) timer = threading.Timer(15, simpleo2control, args=[i, o2channel, objective, tolerance, action]) timer.start() def simpleo2control(i, o2channel, objective, tolerance, action): global timer, o2array if o2array[i] > maximum: fgt_set_pressure(o2channel, 20) time.sleep(1) fgt_set_pressure(o2channel, 0) elif underrange <= o2array[i] <= overrange: fgt_set_pressure(o2channel, 20) time.sleep(0.5) fgt_set_pressure(o2channel, 0) elif o2array[i] < minimum: pass timer = threading.Timer(15, simpleo2control, args=[i, o2channel, objective, tolerance, action]) timer.start() piddestroy = [True, True, True, True] def PIDinitialization(i, o2channel, objective, iterationt, kp, ki, kd): global Piddestroy #print(objective) #objective.get() piddestroy[i] = False objective = float(objective.get()) print(objective) iterationt = float(iterationt.get()) kp = float(kp.get()) ki = float(ki.get()) kd = float(kd.get()) fgt_set_pressure(o2channel, 0) print( "pid should start)") print(iterationt) x = threading.Thread(target=PID, args=(i, o2channel, objective, iterationt, kp, ki, kd)) x.start() #timer = threading.Timer(15, simpleo2control, args=[i, o2channel, objective, interationt, kp, ki, kd]) #timer.start() def PIDrunning(o2channel, output): fgt_set_pressure(o2channel, 20) time.sleep(output) fgt_set_pressure(o2channel, 0) def PIDinitialization(i, o2channel, objective, iterationt, kp, ki, kd,safetyval, minoutput, maxoutput, kp2, kp2actpoint): global Piddestroy #print(objective) #objective.get() piddestroy[i] = False objective = float(objective.get()) print(objective) iterationt = float(iterationt.get()) kp = float(kp.get()) kp2 = float(kp2.get()) kp2actpoint = float(kp2actpoint.get()) ki = float(ki.get()) kd = float(kd.get()) safetyval = float(safetyval.get()) minoutput = float(minoutput.get()) maxoutput= float(maxoutput.get()) fgt_set_pressure(o2channel, 0) print( "pid should start)") print(iterationt) x = threading.Thread(target=PID, args=(i, o2channel, objective, iterationt, kp, ki, kd, safetyval, minoutput, maxoutput, kp2, kp2actpoint)) x.start() def PID(i, o2channel, objective, iterationt, Kp, Ki, Kd, safetyval, minoutput, maxoutput, kp2, kp2actpoint): global piddestroyo # initialize stored data e_prev = 0 t_prev = -100 I = 0 print("pid is starting") # initial control #MV = MV_bar while True: if piddestroy[i] == True: break else: # yield MV, wait for new t, PV, SP SP = float(objective) PV = float(O2array[i]) #*t, PV, SP = yield MV # PID calculations print("calculating PID") e = PV - SP print ("error is:" + str(e) + "for chip:" + str(i)) if e < kp2actpoint and e > 0: Kp = kp2 #Kp = 0.75 P = safetyval * Kp * e #I = I + Ki * e * (t - t_prev) #D = Kd * (e - e_prev) / (t - t_prev) output = P #+ I + D #MV_bar + if output <= 0 : time.sleep(1) elif output <= minoutput: time.sleep(1) elif output >= maxoutput: output = maxoutput PIDrunning(o2channel, output) time.sleep(iterationt) else: PIDrunning(o2channel, output) time.sleep(iterationt) # update stored data for next iteration e_prev = e t_prev = t ####################sensor calibration info############### sensormatrix = np.zeros((4, 6)) print(sensormatrix) sensorcal1 = [False, False, False, False] sensorcal2 = [False, False, False, False] class firstcalibration(): def __init__(self,sensorindex): global sensormatrix, sensorcal1, dataArray #self.code = sensorcode #self.x = np.array([30, 100, 500]).reshape(-1, 1) self.x =np.array([]) self.y = np.array([ 0, 0.50]) for i in self.y: print("Im doing the first calibration") print("put " + str(i) + " N weight and type result: ") input("Press Enter after putting the weight") self.x = np.append(self.x, dataArray[sensorindex]) print(self.x) self.x = self.x.reshape(-1, 1) self.model = LinearRegression() self.model.fit(self.x, self.y) self.r_sq = self.model.score(self.x, self.y) self.intercept = self.model.intercept_ self.slope = self.model.coef_ self.sensorcode = [self.r_sq, self.slope, self.intercept] print(self.sensorcode) sensormatrix[sensorindex][0] = self.r_sq sensormatrix[sensorindex][1] = self.slope sensormatrix[sensorindex][2] = self.intercept sensorcal1[sensorindex] = True return self.sensorcode def calfirstinfo(self): self.sensorcode = [self.intercept, self.r_sq, self.slope] return self.sensorcode def firstcalplot(self): self.o = self.slope * self.x + self.intercept plt.plot(self.x, self.y, "o") #note: he make the y ticks as he wants. #plt.yticks((0, 50, 100)) plt.plot(self.x, self.o) plt.show() class secondcalibration(): def __init__(self, sensorindex): global sensormatrix, sensorcal2, dataArray self.x= np.array([0, 20, 40, 60, 80, 100]) self.d = np.array([]) z=0 while z <= 100: self.read_sensor =0 for i in range (0, 3): print("I am doing the second calibration for " + str(z) + "mbar") print("repetition number " + str(i)) fgt.setpressure(sensorindex,z) time.sleep(1.5) #read sensor self.read_sensor = self.read_sensor + dataArray[sensorindex] fgt.setpressure(sensorindex, 0) time.sleep(1.5) print("I am doing the second calibration for " + str(z) + "mbar") self.read_sensor = self.read_sensor/4 self.d = np.append(self.d, self.read_sensor) z = z + 20 self.curve_fit = np.polyfit(self.x, self.d, 1) print(self.curve_fit) sensormatrix[sensorindex][4, 5] = self.curve_fit[0,1] sensorcal2[index] = True def secondcalinfo(self): print(self.d) self.y = self.curve_fit[1]*np.exp(self.x) + self.curve_fit[0] plt.plot(self.x, self.d, "o") plt.plot(self.x, self.y) #model = LinearRegression() #model.fit(x, self.d) #plt.plot(x, self.d) # plt.plot(x, y, color="red") plt.show() def exportcalibration(): global sensormatrix df = pd.DataFrame(data=sensormatrix, index=["sensor1", "sensor2", "sensor3", "sensor 4" ], columns=["R_square_1st", "m", "n", "R_square_2nd", "A", "B"]) df.to_excel("calibration.xls",index=True) def importcalibration(): global sensormatrix sensormatrix = pd.read_excel("calibration.xls") print (sensormatrix) def startsavingo2(): global writeo2data, t0O2, sheet, bookO2 bookO2 = Workbook() sheet = bookO2.active print("started saving o2") sheet.append(("sensor 1", "sensor 2", "sensor 3", "sensor 4", "time elapsed(s)")) writeo2data = True t0O2 = time.time() return bookO2 def finalsaveo2(): global writeo2data, today writeo2data = False #O2saving.to_excel( str(todayfixed) + "_Oxygen_levels.xls", index=True) def startsaving(): global writedata, t0 print("saving started") writedata = True t0 = time.time() def savingdata(): global writedata, today writedata = False print("saving finished") savevalues.to_excel(str(todayfixed) + "_mechanicalload_values.xls",index=True) ############Loop reading############ t0 = 0 def readingarduino(): global dataArray, savevalues, offset while len(dataArray) != 5: arduinoString = ser.readline().decode("utf-8") arduinoStringC = arduinoString.replace('\x00', '') dataArray = arduinoStringC.split(',') dataArray[0] = float(dataArray[0]) - float(offset[0]) dataArray[1] = float(dataArray[1]) - float(offset[1]) dataArray[2] = float(dataArray[2]) - float(offset[2]) dataArray[3] = float(dataArray[3]) - float(offset[3]) t1 = time.time() - t0 if sensorcal1[0] ==True: dataArray[0] = float(dataArray[0])*sensormatrix[0][1] + sensormatrix[0][2] if sensorcal1[1] ==True: dataArray[1] = float(dataArray[1])*sensormatrix[1][1] + sensormatrix[1][2] if sensorcal1[2] ==True: dataArray[2] = float(dataArray[2])*sensormatrix[2][1] + sensormatrix[2][2] if sensorcal1[2] ==True: dataArray[2] = float(dataArray[2])*sensormatrix[2][1] + sensormatrix[2][2] if writedata == True: # end = time.time() # total = start - end() # savevalues = savevalues.append({'sensor 1': dataArray[0], 'sensor 2': dataArray[1], 'sensor 3': dataArray[2], "sensor 4": dataArray[3]}, ignore_index=True) savevalues = savevalues.append({'sensor 1': float(dataArray[0]), 'sensor 2': float(dataArray[1]), 'sensor 3': float(dataArray[2]), "sensor 4": float(dataArray[3]), "time elapsed (s)": t1}, ignore_index=True) #for i in dataArray: #index = list.index(i) #if sensorcal1[index] == True: #dataArray[i] = dataArray[i]*10 #* sensormatrix[index][1] + sensormatrix[index][2] #return dataArray #elif sensorcal2[index] == True: #dataArray[i] = sensormatrix[index][4]*np.log(dataArray[i]) + sensormatrix[index][5] #else: #pass #return dataArray ########################################### #def tare(arg1, arg2): #global offset1, dataArray, offset2, offset3, offset4 #arg1 = dataArray[int(arg2)] #print(arg1) def tare(i): global offset, dataArray offset[i] = dataArray[i] print (offset[i]) #print(float(dataArray[0]) - float(offset1)) def submit(arg1, arg2, arg3): arg1.set_ylim(float(arg2.get()), float(arg3.get())) plt.pause(0.5) #print(minvalue) ################################################### O2array = [0, 0, 0, 0] t0O2 = 0 def o2iteration(): global t, now, oxygenX, oxygenY, oxygenZ, oxygenD, O2measures, O2array, O2saving, bookO2 if firestingconnect == True: O2measures = firesting.measure() O2measures= list(O2measures.values()) O2array = (float(O2measures[0]["percentO2"]), float(O2measures[1]["percentO2"]), float(O2measures[2]["percentO2"]), float(O2measures[3]["percentO2"])) oxygenX = O2array[0] oxygenY = O2array[1] oxygenZ = O2array[2] oxygenD = O2array[3] t1O2 = time.time() - t0O2 if writeo2data == True: #O2saving = O2saving.append({"sensor 1": O2array[0], "sensor 2": O2array[1], "sensor 3": O2array[2], "sensor 4": O2array[3], "time elapsed (s)": t1O2}, ignore_index=True ) #O2saving = O2saving.append({"sensor 1": [oxygenX], "sensor 2": [oxygenY], "sensor 3": [oxygenZ], "sensor 4": [oxygenD]}) print("yay") O2saving = (float(O2array[0]), float(O2array[1]), float(O2array[2]), float(O2array[3]), t1O2) sheet.append(O2saving) bookO2.save(str(todayfixed) + "_Oxygen_levels.xlsx") print("saving O2 new style") timer = threading.Timer(0.3, o2iteration) timer.start() #p2 = multiprocessing.Process(target=o2iteration) #p2.start() #p2.join() #readingarduino() #writedata = True ######################################## def animate(i): global t, accX, accY, accZ, accD, now, df1, mechdatasaving, dataArray, df, writedata, savevalues, offset1, offset2, offset3, offset4 #if arduinoconnect == True: #while len(dataArray) != 5: trial = (float(dataArray[0]) - float(offset1)) #trial2 = (float(dataArray[1]) - float(offset2)) #trial3 = (float(dataArray[2]) - float(offset3)) #trial4 = (float(dataArray[3]) - float(offset4)) # index = list.index(i) accX.append(trial) accY.append(float(dataArray[1])- float(offset2)) accZ.append(float(dataArray[2]) - float(offset3)) accD.append(float(dataArray[3])- float(offset4)) #print(dataArray) accX.pop(0) accY.pop(0) accZ.pop(0) accD.pop(0) #print(dataArray) graphX.set_data(t, accX) graphY.set_data(t, accY) graphZ.set_data(t, accZ) graphD.set_data(t, accD) return graphX, graphY, graphZ, graphD def animate2(i): global t, accX, accY, accZ, accD, writedata, writedata2, writedata3, writedata4, offset1, dataArray, prueba, firesting, accO21, accO22, accO23, accO24, gato2, O2array #graphO21, graphO22, graphO23, graphO24,O2datarray #O2datarray = [] #O2datarray = [0, 0, 0, 0] accO21.append(O2array[0]) accO22.append(O2array[1]) accO23.append(O2array[2]) accO24.append(O2array[3]) print(O2array) accO21.pop(0) accO22.pop(0) accO23.pop(0) accO24.pop(0) #print("its working") graphO21.set_data(t, accO21) graphO22.set_data(t, accO22) graphO23.set_data(t, accO23) graphO24.set_data(t, accO24) #root.update() return graphO21, graphO22, graphO23, graphO24, #################################################################################### delay = 100 delay2 = 1000 anim = animation.FuncAnimation(fig, animate, init_func=init, interval=delay, blit=True) anim2 = animation.FuncAnimation(fig, animate2, init_func=init, interval=delay2, blit=True) #fig.show() fig.canvas.draw() #fig2.show() fig2.canvas.draw() #plt.ion() #plt.show() #root.mainloop()