
"""
Created on Wed Aug 30 14:48:13 2023

@author: Admin
"""


from os import listdir
from os.path import isfile, join
import serial 

import numpy as np
import pandas as pd 
import time 


import propar

#step1: be sure to the address of the files that the ftir data is exported is matching to line 11 (mypath)
#mypath = "abhilash\\soft\\test mfc code\\Dummy Data"

mypath="C:\\Users\\Dr.AJAY K SINGH\\Desktop\\RUCHI\\23-04-2024"



onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]


#step2: make sure that pump and the potentiostat is correctly addressed in the line 16 and 17
pump_1 = serial.Serial("COM13",9600) #HPLC Pump 
port = serial.Serial("COM1",115200)
printer = serial.Serial("COM14", 115200, timeout=1)
MFC = propar.instrument('COM8')
port = serial.Serial("COM7",115200) #power_supply

def gas_flow(set_val):
 
   MFC.writeParameter(206, set_val)
   
   
def valve_reset(): 
    #run if valve is refusing to close, i.e. in forced full open mode
    
    MFC.writeParameter(12, 0)

    return "valve was reset"
    

def function(flowrate_1,flow_g,v,i,time_hold):
    
     #set the pumps with the flowrate as the desired flowrate for the function

    
    fr_1 = flowrate_1*1000   #ml/min
    pump_1.write(('flow:'+ str(fr_1) + '\r').encode())
    time.sleep(0.1)
       
    #pumps run
    pump_1.write(b'on\r')
    time.sleep(0.1)
    gas_flow(flow_g)
    
    vol = v
    curr = i
    port.write(('VOLT '+str(vol)+'\r\n').encode())     #to change the voltge we need to use "VOLT 1" command 
    port.write(('CURR '+str(curr)+'\r\n').encode())    #to change the current we need to use "CURR 1" command
    
    time.sleep(0.1)
    
    time.sleep(time_hold)

#step 4:grab the line 93 and f9
from skopt.optimizer import Optimizer


#step5:in line 96 we have to define the range that (flowrate,flow_gas) (from,to) and after (anytime) appllying changes you need to grab the line 96 and f9
#flowrates are in ml/min
bounds = [(0.1,0.5),(10,30),(12.5,14.5),(4.9,5.0)]
#step 6: grab the line 100 and f9
opter =Optimizer(bounds,base_estimator='gp',n_initial_points=3,acq_func="EI",random_state=np.random.randint(3326))


#step7: to selecte number of the cycles that you have to do the experiment and then grab the line 104 to 121 and f9: the closed loop experimentation is initiated
number_of_cycles =22
results = []
flowrates_1 = []
flow_g = []
vs = []
currents = []


product_percentage=True #set to true if product wavelengths being monitored

if product_percentage == True:
    val=1
else:
    val=-1


# Step 8: Test Tubes on Printer
USE_PRINTER = True
REST_HEIGHT = 200
X_HOME = -5
Y_HOME = 20
Z_HOME = 175
DEFAULT_PUMP_TIME="1"
# Distance between test tubes
X_SPACING=20
Y_SPACING=20
# Number of test tubes
X_ROWS = 11
Y_COLUMNS = 4

def send_cmd(cmd):
    print(cmd)
    printer.write(f"{cmd}\n".encode("ASCII"))

def move(x=None, y=None, z=None):
    s = "G0"
    if x is not None:
        s += f"X{x}"
    if y is not None:
        s += f"Y{y}"
    if z is not None:
        s += f"Z{z}"
    
    s+= "F5000"
    send_cmd(s)

def printer_positions():
    for j in range(Y_COLUMNS):
        for i in range(X_ROWS):
            if j%2==1:
                yield (X_HOME + (X_ROWS - 1 - i) * X_SPACING, Y_HOME + j * Y_SPACING, Z_HOME)
            else:
                yield (X_HOME + i * X_SPACING, Y_HOME + j * Y_SPACING, Z_HOME)

# Run this.
tube_location = list(printer_positions())

try:
    valve_reset()
    for i in range(number_of_cycles):
        move(*tube_location[2*i])
        asked = opter.ask()
        print(asked[0])
        print(asked[1])
        print(asked[2])
        print(asked[3])
        
        time_hold_reaction=800#time for each run

        function(asked[0],asked[1],asked[2],asked[3],time_hold_reaction)
        move(*tube_location[2*i+1])
        
        #hplc input value
        
        time.sleep(1300) #for collection in 2nd test tubeA
        function(0,0,0.01,0.001,0) #turns off pump and power supply
        
        offline_told = float(input("give the results from offline analysis\n"))
        opter.tell(asked,offline_told*(-val))

        results.append(offline_told)
        flowrates_1.append(asked[0])
        flow_g.append(asked[1])

        dict1 = {"flowrate_1":flowrates_1,"flow_g":flow_g,"area-results":results}
        df2 = pd.DataFrame(dict1)
        df2.to_csv("output round "+str(i)+".csv")
finally:
    pump_1.write(b'off\r')        
    gas_flow(0)
