#====================================================================
#	Python code converted from JAVA for FeedBack Loop Config GUI
#
#	Auth: 11/19/2018 Zheng Sun (zsun5637)
#
#	note: need AIDA AND MATLABCONTROL for f and g matrix window 
#		  need AIDA for all import Model DB buttons
#	      need Timing for timing pattern window
#	      need overview and function tab
#====================================================================
import sys
import epics
PV = epics.PV
from os import path
import os
from pydm import Display
from pydm.widgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore, QtGui, QtWidgets
from pydm.widgets.checkbox import PyDMCheckbox
from qtpy.QtWidgets import QCheckBox
from qtpy.QtCore import Qt
from classCommonPV import *
from classMeasurement import *
from classActuators import *
from classState import *
from classMatrices import *
from classOrbit import *
from classTime import *
from threading import Thread
from scipy.io import loadmat
import numpy as np
import copy

class MyDisplay(Display):
        def __init__(self, parent=None, args=[]):
                super(MyDisplay, self).__init__(parent=parent, args=args)
                # set to measurement page at loading
                self.ui.page.setCurrentIndex(0)
                self.ui.measButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.tableFormat()
                self.centerCheckBox()


                # FBCK:arg1:arg2 and arg3:
                # command line : pydm filename FB01 1 2  --> commonPVstring =  FBCK:FB01:TR02:
                self.slotNums = []
                if len(sys.argv) == 5 :
                        self.currFBIOC = sys.argv[2]
                        self.currFBType = int(sys.argv[3])
                        self.slot = int(sys.argv[4])-1
                if len(sys.argv) == 6 :
                        self.currFBIOC = sys.argv[2]
                        self.currFBType = sys.argv[3]
                        self.slot = int(sys.argv[4])-1
                        self.showTabs = True
                        if int(sys.argv[5]) > 0:
                                self.showFunctionTab = True
                        else:
                                self.showFunctionTab = False

                if self.currFBType == 0:
                        self.currFBTypeStr = 'GN'
                if self.currFBType == 2:
                        self.currFBTypeStr = 'LG'
                if self.currFBType == 1:
                        self.currFBTypeStr = 'TR'

                for n in range(0,11):
                        self.slotNums.append(n)
                        if n < 9:
                                self.slotNums[n] = '0' + str((n+1))
                        else:
                                self.slotNums[n] = ''+ str((n+1))
                self.currFBSlot = self.slotNums[self.slot]

                # init FBCK:arg1:arg2+arg3:   testing: FB01 1 2 --> FBCK:FB01:TR02
                self.commonPVstring = pvString(self.currFBIOC,self.currFBTypeStr,self.currFBSlot)


                self.fMatrixCheckArray = [] # array of index = True in measurements list, used for F Matrix window
                self.gMatrixLeftCheckArray = [] # array of index = True in state list, used for G Matrix window
                self.gMatrixTopCheckArray = []  # array of index = True in actuators list, used for G Matrix window

                #==================================================== Measurement Window ==============================================================================
                # postfix 'Array' => arrays to store data  from PVs, from get() functions
                self.measUsedBox = []
                self.measCamodeBox = []
                self.measUsedArray = []
                self.measCamodeArray = []
                self.measLoloArray = []
                self.measHihiArray = []
                self.measDispArray = []
                self.measUnitArray = []
                self.measNameArray =  []

                self.measTableHighlightArray = [] # array storing the index of Highlighting rows
                self.measTableChangedArray = [] # array storing the index of value changed rows

                # init measurement class with PV attributes
                self.measurement = classMeasurement(self.commonPVstring,'USED','CAMODE','DEVNAME','.EGU','MEASDSPR','LOLO','HIHI','MEASNUM')
                self.measDevNameArray = self.measurement.devnameget()
                self.measNameArray = self.measurement.measArrayget()
                self.measUsedArray = self.measurement.useArrayget()
                self.measCamodeArray = self.measurement.camodeArrayget()
                self.measLoloArray = copy.deepcopy(self.measurement.loloArrayget())
                self.measHihiArray = copy.deepcopy(self.measurement.hihiArrayget())
                self.measDispArray = copy.deepcopy(self.measurement.dispArrayget())
                self.ui.measTable.setColumnCount(6)
                self.ui.measTable.setRowCount(self.measurement.arraysize)



                for n in range(0,self.measurement.arraysize):

                        self.measTableHighlightArray.append(0) # init to no highlights and no changes
                        self.measTableChangedArray.append(0)


                        #  measurements device name added to the table column 3
                        self.ui.measTable.setItem(n,2,QTableWidgetItem(self.measNameArray[n]))
                        self.ui.measTable.item(n,2).setFlags(QtCore.Qt.ItemIsEnabled)

                        # list of empty checkboxes, init "CHOSEN" states 'YES' or 'No' according to PVs, added to the table column 1
                        self.measUsedBox.append(QCheckBox())
                        if self.measUsedArray[n] == 'YES':

                                self.fMatrixCheckArray.append(1)                        # the f matrix window needs to know which measurements are checked to True

                                self.measUsedBox[n].setChecked(True)
                        else:
                                self.measUsedBox[n].setChecked(False)

                                self.fMatrixCheckArray.append(0)

                        self.measUsedBox[n].setStyleSheet("margin-left:120%;")  # formatting
                        self.measUsedBox[n].stateChanged.connect(self.doubleStateChange)

                        self.ui.measTable.setCellWidget(n,0,self.measUsedBox[n])

                        # list of empty checkboxes, init "CAMODE" states 'YES' or 'No' according to PVs, added to the table column 2
                        self.measCamodeBox.append(QCheckBox())
                        if self.measCamodeArray[n] == 'YES':
                                self.measCamodeBox[n].setChecked(True)
                        else:
                                self.measCamodeBox[n].setChecked(False)

                        self.measCamodeBox[n].setStyleSheet("margin-left:120%;")  # formatting

                        self.measCamodeBox[n].stateChanged.connect(self.measCamodeBoxChange)
                        self.ui.measTable.setCellWidget(n,1,self.measCamodeBox[n])

                        # add LOLO data to column 5
                        self.ui.measTable.setItem(n,4,QTableWidgetItem(str(self.measLoloArray[n])))

                        # add HIHI data to column 6
                        self.ui.measTable.setItem(n,5,QTableWidgetItem(str(self.measHihiArray[n])))

                        # add Dispersion data to column 4
                        self.ui.measTable.setItem(n,3,QTableWidgetItem(str(self.measDispArray[n])))
                #==================================================================================================================================
                # format, center widgets
                        for j in range (2,6):
                                self.ui.measTable.item(n,j).setTextAlignment(Qt.AlignCenter)
                # ============================================ Actuator  Window ====================================================================
                # postfix 'Array' => arrays to store data  from PVs, from get() functions
                self.actUsedBox = []
                self.actCamodeBox = []
                self.actUsedArray = []
                self.actCamodeArray = []
                self.actLoloArray = []
                self.actHihiArray = []
                self.actEnergyArray = []
                self.actUnitArray = []

                self.actTableHighlightArray = [] #  array storing the index of Highlighting rows
                self.actTableChangedArray = [] # array storing the index of value changed rows

                # init actuator class with PV attributes
                self.actuator = classActuator(self.commonPVstring,'USED','CAMODE','DEVNAME','.EGU','ACTENERGY','LOLO','HIHI','ACTNUM')
                self.actDevNameOnlyArray = self.actuator.devNameget()
                self.actDevNameArray = self.actuator.actArrayget()
                self.actUsedArray = self.actuator.useArrayget()
                self.actCamodeArray = self.actuator.camodeArrayget()
                self.actLoloArray = copy.deepcopy(self.actuator.loloArrayget())
                self.actHihiArray = copy.deepcopy(self.actuator.hihiArrayget())
                self.actEnergyArray = copy.deepcopy(self.actuator.energyArrayget())
                self.actUnitArray = self.actuator.unitArrayget()
                self.ui.actTable.setColumnCount(6)
                self.ui.actTable.setRowCount(self.actuator.arraysize)


                for n in range(0,self.actuator.arraysize):

                        self.actTableHighlightArray.append(0) # init no Highlights and no value changes
                        self.actTableChangedArray.append(0)

                        # add actuator device names to table column 3
                        self.ui.actTable.setItem(n,2,QTableWidgetItem(self.actDevNameArray[n]))
                        self.ui.actTable.item(n,2).setFlags(QtCore.Qt.ItemIsEnabled)

                        # list of empty checkboxes, init "CHOSEN" states 'YES' or 'No' according to PVs, added to the table column 1
                        self.actUsedBox.append(QCheckBox())
                        if self.actUsedArray[n] == 'YES':

                                self.gMatrixTopCheckArray.append(1)                     # the g matrix window needs to know which acctuator boxes are checked

                                self.actUsedBox[n].setChecked(True)
                        else:
                                self.actUsedBox[n].setChecked(False)

                                self.gMatrixTopCheckArray.append(0)

                        self.actUsedBox[n].setStyleSheet("margin-left:120%;")   # formatting

                        self.ui.actUsedBox[n].stateChanged.connect(self.gMatrixChange)
                        self.ui.actTable.setCellWidget(n,0,self.actUsedBox[n])


                        #list of empty checkboxes, init "CAMODE" states 'YES' or 'No' according to PVs, added to the table column 2
                        self.actCamodeBox.append(QCheckBox())
                        if self.actCamodeArray[n] == 'YES':
                                self.actCamodeBox[n].setChecked(True)
                        else:
                                self.actCamodeBox[n].setChecked(False)
                        self.actCamodeBox[n].setStyleSheet("margin-left:120%;")
                        self.ui.actCamodeBox[n].stateChanged.connect(self.actCamodeBoxChange)
                        self.ui.actTable.setCellWidget(n,1,self.actCamodeBox[n])

                        # add LOLO data to column 4
                        self.ui.actTable.setItem(n,3,QTableWidgetItem(str(self.actLoloArray[n])))

                        # add HIHI data to column 5
                        self.ui.actTable.setItem(n,4,QTableWidgetItem(str(self.actHihiArray[n])))

                        # add Energy data to column 6
                        self.ui.actTable.setItem(n,5,QTableWidgetItem(str(self.actEnergyArray[n])))
                # ================================================================================================================
                # format, center widgets
                        for j in range (2,6):
                                self.ui.actTable.item(n,j).setTextAlignment(Qt.AlignCenter)



                # ============================================ State  Window ==========================================
                # postfix 'Array' => arrays to store data  from PVs, from get() functions
                self.stateUsedBox = []
                self.stateUsedArray = []
                self.stateSetPointArray = []
                self.stateLoloArray = []
                self.stateUnitArray = []
                self.stateHihiArray = []

                self.stateTableHighlightArray = []      #  array storing the index of Highlighting rows
                self.stateTableChangedArray = []        # array storing the index of value changed rows

                # init class state with PV attributes
                self.state = classState(self.commonPVstring, 'USED', 'NAME', 'DES', 'LOLO', 'HIHI', 'STATENUM', 'PGAIN','IGAN','IGAINERRNUM')
                self.statePgain = self.state.pgainget()
                self.stateDevNameArray = self.state.devNameget()
                self.stateSetPointArray = self.state.setPointArrayget()
                self.stateUsedArray = self.state.useArrayget()
                self.stateLoloArray = self.state.loloArrayget()
                self.stateHihiArray = self.state.hihiArrayget()
                self.stateIgain = self.state.igainget()
                self.stateErrNum = self.state.errget()
                self.ui.stateTable.setColumnCount(5)
                self.ui.stateTable.setRowCount(self.state.arraysize)

                for n in range(0,self.state.arraysize):

                        self.stateTableHighlightArray.append(0)  # init no Highlights and no value changes
                        self.stateTableChangedArray.append(0)


                        # add state device names to table column 2
                        self.ui.stateTable.setItem(n,1,QTableWidgetItem(self.stateDevNameArray[n]))
                        self.ui.stateTable.item(n,1).setFlags(QtCore.Qt.ItemIsEnabled)

                        #  list of empty checkboxes, init "CHOSEN" states 'YES' or 'No' according to PVs, added to the table column 1
                        self.stateUsedBox.append(QCheckBox())
                        if self.stateUsedArray[n] == 'YES':

                                self.gMatrixLeftCheckArray.append(1)            # the g matrix window needs to know which state  boxes are checked
                                self.stateUsedBox[n].setChecked(True)
                        else:
                                self.gMatrixLeftCheckArray.append(0)
                                self.stateUsedBox[n].setChecked(False)

                        self.stateUsedBox[n].setStyleSheet("margin-left:150%;")
                        self.ui.stateUsedBox[n].stateChanged.connect(self.gMatrixChange)
                        self.ui.stateTable.setCellWidget(n,0,self.stateUsedBox[n])

                        #  add LOLO data to column 4
                        self.ui.stateTable.setItem(n,3,QTableWidgetItem(str(round(self.stateLoloArray[n],3))))

                        #  add Hihi data to column 5
                        self.ui.stateTable.setItem(n,4,QTableWidgetItem(str(round(self.stateHihiArray[n],3))))

                        #   add Set Point data to column 4
                        self.ui.stateTable.setItem(n,2,QTableWidgetItem(str(round(self.stateSetPointArray[n],3))))

                        # if feedback type is Longitudinal   show all 3 numbers Pgain, I-gain and  I-gain-error
                        # else show only P Gain
                        if self.currFBTypeStr == 'LG':
                                self.ui.iGainText.show()
                                self.ui.errText.show()
                                self.ui.iGainVal.show()
                                self.ui.errVal.show()
                                self.ui.pGainVal.setText(str(self.statePgain))
                                self.ui.iGainVal.setText(str(self.stateIgain))
                                self.ui.errVal.setText(str(self.stateErrNum))

                        else:
                                self.ui.iGainText.hide()
                                self.ui.errText.hide()
                                self.ui.iGainVal.hide()
                                self.ui.errVal.hide()
                                self.ui.pGainVal.setText(str(self.statePgain))
                # ======================================================================================
                # format, center widgets
                        for j in range (1,5):
                                self.ui.stateTable.item(n,j).setTextAlignment(Qt.AlignCenter)




                # ============================================Matrix Window ==========================================
                self.fMatrixData = []
                self.gMatrixData = []
                self.fMatrixPolyData = []
                self.fMatrixFirstTime = True
                self.gMatrixFirstTime = True
                self.matLink = '/u1/lcls/matlab/Feedback/Matrices/'
                self.matrices = classMatrices(self.commonPVstring, 'FMATRIX','GMATRIX','POLYVALS' )
                self.fMatrixData = self.matrices.fmatrixget()
                self.fMatrixData = self.fMatrixData[:self.measurement.arraysize*5]      # cut out useless data (not necessary)
                self.gMatrixWinData = self.matrices.gmatrixget()[:len(self.gMatrixLeftCheckArray)*len(self.gMatrixTopCheckArray)] # cut out useless data

                self.fMatrixPolyData = self.matrices.fPolyget() # polynomials data
                self.fMatrixNameArray = self.measDevNameArray

                self.gMatrixLeftDevNameArray = self.state.devNameget()
                self.gMatrixTopNameArray = self.actDevNameOnlyArray

                self.ui.fMatrixTable.setColumnCount(6)
                self.ui.importFbutton.clicked.connect(self.importMatrix)
                self.ui.importGbutton.clicked.connect(self.importMatrix)
                self.launchName = str(PV(self.commonPVstring.pvstring + "NAME").get())

                self.ui.polyButton.clicked.connect(self.fMatrixGetData)

                if self.launchName == "UndulatorLaunch":
                        self.ui.polyButton.setText(" Get Feedback Matrix Polynomials  ")
                # ==================================================================================================================


                # ============================================ Reference Orbit Window ==========================================
                self.refOrbitArray = []
                self.actRefArray = []

                self.refOrb = classOrbit(self.commonPVstring, 'REFORBIT','ACTREF')
                self.refOrbNameArray = self.measDevNameArray
                self.actRefNameArray = self.actDevNameOnlyArray
                self.refOrbArray = self.refOrb.refOrbGet(len(self.refOrbNameArray))
                self.actRefArray = self.refOrb.actRefGet(len(self.actRefNameArray))

                self.ui.refOrbTable.setColumnCount(8)
                self.ui.refOrbTable.setRowCount((len(self.refOrbArray)/4.1)+1)
                self.ui.actRefTable.setColumnCount(4)
                self.ui.actRefTable.setRowCount((len(self.actRefArray)/2.1)+1)
                # ==================================================================================================================


                # ============================================ Time Patterns Window ==========================================
                # not completed. need  "edu.slac.stanford.timing"
                self.timePat = classTime(self.commonPVstring,'TOTALPOI','POI1','POI2','POI3','POI4')
                self.poi1Array = self.timePat.poi1Arrayget()
                self.poi2Array = self.timePat.poi2Arrayget()
                self.poi3Array = self.timePat.poi3Arrayget()
                self.poi4Array = self.timePat.poi4Arrayget()
                self.poiTotalArray = self.timePat.poitotalArrayget()

                self.ui.patternMenu.addItem(str(1))
                self.ui.patternMenu.addItem(str(2))
                self.ui.patternMenu.addItem(str(3))
                self.ui.patternMenu.addItem(str(4))
                # ==================================================================================================================


                # get limits from device button
                self.ui.measGetLimitsButton.clicked.connect(self.measGetLimits)
                self.ui.actGetLimitsButton.clicked.connect(self.actGetLimits)

                # get disp from DB
                self.ui.measGetDispButton.clicked.connect(self.measGetDisp)
                self.ui.actGetEnergyButton.clicked.connect(self.actGetEnergy)

                # check all box functions
                self.ui.measCheckBox.stateChanged.connect(self.checkAll)
                self.ui.actCheckBox.stateChanged.connect(self.checkAll1)

                # switch screnss functions
                self.ui.measButton.clicked.connect(self.changePage1)
                self.ui.stateButton.clicked.connect(self.changePage2)
                self.ui.actButton.clicked.connect(self.changePage3)
                self.ui.matrixButton.clicked.connect(self.changePage4)
                self.ui.refOrbButton.clicked.connect(self.changePage5)
                self.ui.timeButton.clicked.connect(self.changePage6)

                # connect save functions to the SAVE buttons
                self.ui.saveButton.clicked.connect(self.save)

                # connect highlighting functions to mouse Highlighting
                self.ui.measTable.cellClicked.connect(self.measRowHighlight)
                self.ui.actTable.cellClicked.connect(self.actRowHighlight)

                # signal for changes in the tables - init NO changes
                self.measItemChange = False
                self.ui.measTable.itemChanged.connect(self.measItemChanged)
                self.actItemChange = False
                self.ui.actTable.itemChanged.connect(self.actItemChanged)
                self.stateItemChange = False
                self.ui.stateTable.itemChanged.connect(self.stateItemChanged)
                self.fMatrixItemChange = False
                self.ui.fMatrixTable.itemChanged.connect(self.fMatrixItemChanged)
                self.gMatrixItemChange = False
                self.ui.gMatrixTable.itemChanged.connect(self.gMatrixItemChanged)
                self.refOrbItemChange = False
                self.ui.refOrbTable.itemChanged.connect(self.refOrbItemChanged)
                self.actRefItemChange = False
                self.ui.actRefTable.itemChanged.connect(self.actRefItemChanged)


        #---------------SAVE Buttons ---------------------------------------
        # once the code is completed, delete the print statements and uncomment all line starting "epics.put"
        def save(self):
                if self.measItemChange == True:
                        tempUsedArray = []
                        tempCamodeArray = []
                        tempLoprName = []
                        tempHoprName = []
                        for n in range(0,self.measurement.arraysize):
                                if self.measUsedBox[n].checkState() == 2 :
                                        tempUsedArray.append(1)
                                else:
                                        tempUsedArray.append(0)
                                if self.measCamodeBox[n].checkState() == 2 :
                                        tempCamodeArray.append(1)
                                else:
                                        tempCamodeArray.append(0)

                                tempHoprName.append(self.measDevNameArray[n] + '.HOPR')
                                tempLoprName.append(self.measDevNameArray[n] + '.LOPR')
                                #epics.caput(tempHoprName[n],self.measHihiArray[n])
                                #epics.caput(tempLoprName[n],self.measLoloArray[n])
                        print(tempHoprName)
                        print(tempLoprName)
                        print(self.measHihiArray)
                        print(self.measLoloArray)

                        print(self.commonPVstring.pvstring + self.measurement.usePVstring)
                        print(tempUsedArray)
                        #epics.caput(self.commonPVstring.pvstring+self.measurement.usePVstring,tempUsedArray)

                        print(self.commonPVstring.pvstring + self.measurement.camodePVstring)
                        print(tempCamodeArray)
                        #epics.caput(self.commonPVstring.pvstring+self.measurement.camodePVstring,tempCamodeArray)

                        print(self.commonPVstring.pvstring+self.measurement.dispPVstring)
                        print(self.measDispArray)
                        #epics.caput(self.commonPVstring.pvstring+self.measurement.dispPVstring,self.measDispArray)

                if self.actItemChange == True:
                        tempUsedArray = []
                        tempCamodeArray = []
                        tempLoprName = []
                        tempHoprName = []
                        for n in range(0,self.actuator.arraysize):
                                if self.actUsedBox[n].checkState() == 2 :
                                        tempUsedArray.append(1)
                                else:
                                        tempUsedArray.append(0)
                                if self.actCamodeBox[n].checkState() == 2 :
                                        tempCamodeArray.append(1)
                                else:
                                        tempCamodeArray.append(0)

                                tempHoprName.append(self.actDevNameOnlyArray[n] + '.HOPR')
                                tempLoprName.append(self.actDevNameOnlyArray[n] + '.LOPR')
                                #epics.caput(tempHoprName[n],self.actHihiArray[n])
                                #epics.caput(tempLoprName[n],self.actLoloArray[n])
                        print(tempHoprName)
                        print(tempLoprName)
                        print(self.actHihiArray)
                        print(self.actLoloArray)

                        print(self.commonPVstring.pvstring + self.actuator.usePVstring)
                        print(tempUsedArray)
                        #epics.caput(self.commonPVstring.pvstring+self.actuator.usePVstring,tempUsedArray)

                        print(self.commonPVstring.pvstring + self.actuator.camodePVstring)
                        print(tempCamodeArray)
                        #epics.caput(self.commonPVstring.pvstring+self.actuator.camodePVstring,tempCamodeArray)


                        print(self.commonPVstring.pvstring+self.actuator.energyPVstring)
                        print(self.actEnergyArray)
                        #epics.caput(self.commonPVstring.pvstring+self.actuator.energyPVstring,self.actEnergyArray)

                if self.stateItemChange == True:
                        tempHihiName = []
                        tempLoloName = []
                        tempUsedArray = []
                        for n in range(0,self.state.arraysize):
                                if self.stateUsedBox[n].checkState() == 2 :
                                        tempUsedArray.append(1)
                                else:
                                        tempUsedArray.append(0)
                                tempHihiName.append(self.commonPVstring.pvstring + 'S' + str((n+1)) + self.state.hihiPVstring)
                                tempLoloName.append(self.commonPVstring.pvstring + 'S' + str((n+1)) + self.state.loloPVstring)
                                #epics.caput(tempHihiName[n], self.stateHihiArray[n])
                                #epics.caput(temploloName[n], self.stateLoloArray[n])
                        print(tempHihiName)
                        print(self.stateHihiArray)
                        print(tempLoloName)
                        print(self.stateLoloArray)

                        print(self.commonPVstring.pvstring + self.state.usePVstring)
                        print(tempUsedArray)
                        #epics.caput(self.commonPVstring.pvstring+self.state.usePVstring,tempUsedArray)

                        print(self.commonPVstring.pvstring+self.state.setpointPVstring)
                        print(self.stateSetPointArray)
                        #epics.caput(self.commonPVstring.pvstring+self.state.setpointPVstring,self.stateSetPointArray)
                if self.fMatrixItemChange == True or self.gMatrixItemChange == True:
                        #print(self.commonPVstring.pvstring + self.matrices.fmatrixPVstring)
                        #print(self.fMatrixData)
                        #print(self.commonPVstring.pvstring + self.matrices.gmatrixPVstring)
                        print(self.fMatrixData)
                        print(self.gMatrixWinData)
                        #epics.caput(self.commonPVstring.pvstring + self.matrices.fmatrixPVstring,self.fMatrixData)
                        #epics.caput(self.commonPVstring.pvstring + self.matrices.gmatrixPVstring,self.gMatrixWinData)

                if self.refOrbItemChange == True:
                        print(self.commonPVstring.pvstring + self.refOrb.refOrbPVstring)
                        print(self.refOrbArray)
                        #epics.caput(self.commonPVstring.pvstring +self.refOrb.refOrbPVstring, self.refOrbArray)

                if self.actRefItemChange == True:
                        print(self.commonPVstring.pvstring + self.refOrb.actRefPVstring)
                        print(self.actRefArray)
                        #epics.caput(self.commonPVstring.pvstring +self.refOrb.actRefPVstring, self.actRefArray)

        #------------------Get Limits Buttons--------------------------
        def measGetLimits(self):
                # refresh limits data and update the table
                for n in range(0,self.measurement.arraysize):
                        if self.measTableHighlightArray[n] == 1 :
                                self.ui.measTable.setItem(n,4,QTableWidgetItem(str(self.measurement.loloArray[n])))
                                self.ui.measTable.setItem(n,5,QTableWidgetItem(str(self.measurement.hihiArray[n])))
                                self.ui.measTable.item(n,4).setTextAlignment(Qt.AlignCenter)
                                self.ui.measTable.item(n,5).setTextAlignment(Qt.AlignCenter)

        def actGetLimits(self):
                # refresh limits data and update the table
                for n in range(0,self.actuator.arraysize):
                        if self.actTableHighlightArray[n] == 1 :
                                self.ui.actTable.setItem(n,3,QTableWidgetItem(str(self.actuator.loloArray[n])))
                                self.ui.actTable.setItem(n,4,QTableWidgetItem(str(self.actuator.hihiArray[n])))
                                self.ui.actTable.item(n,3).setTextAlignment(Qt.AlignCenter)
                                self.ui.actTable.item(n,4).setTextAlignment(Qt.AlignCenter)

        def measGetDisp(self):
                # refresh dispersion data and update the table
                #for n in range(0,self.measurement.arraysize):
				# ====================== AIDA ================================
				#self.measDispArray = AIDA
                #       self.ui.measTable.item(n,3).setTextAlignment(Qt.AlignCenter)
                return

        def actGetEnergy(self):
                # refresh energy data and update the table
                #for n in range(0,self.actuator.arraysize):
				# ====================== AIDA ================================
				#self.actEnergyArray = AIDA
                #       self.ui.actTable.item(n,5).setTextAlignment(Qt.AlignCenter)
                return

        # measurement and actuator screen check all box
        def checkAll1(self):
                if self.ui.actCheckBox.isChecked() == True:
                        for n in range(0,len(self.actCamodeBox)):
                                self.actCamodeBox[n].setChecked(True)
                else:
                        for n in range(0,len(self.actCamodeBox)):
                                self.actCamodeBox[n].setChecked(False)

        def checkAll(self):
                if self.ui.measCheckBox.isChecked() == True:
                        for n in range(0,len(self.measCamodeBox)):
                                self.measCamodeBox[n].setChecked(True)
                else:
                        for n in range(0,len(self.measCamodeBox)):
                                self.measCamodeBox[n].setChecked(False)



        # table multiple lines selection and table format
        def tableFormat(self):
                self.ui.measTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.actTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.stateTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.fMatrixTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.gMatrixTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.refOrbTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.actRefTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)


                self.ui.refOrbTable.verticalHeader().setResizeMode(QHeaderView.Stretch)
                self.ui.actRefTable.verticalHeader().setResizeMode(QHeaderView.Stretch)

                self.ui.measTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                self.ui.actTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                self.ui.stateTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                self.ui.fMatrixTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                self.ui.gMatrixTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                #self.ui.refOrbTable.setSelectionBehavior(QAbstractItemView.SelectRows)
                #self.ui.actRefTable.setSelectionBehavior(QAbstractItemView.SelectRows)


                self.ui.measTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                self.ui.actTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                self.ui.stateTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                self.ui.fMatrixTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                self.ui.gMatrixTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                #self.ui.refOrbTable.setSelectionMode(QAbstractItemView.ExtendedSelection)
                #self.ui.actRefTable.setSelectionMode(QAbstractItemView.ExtendedSelection)

                self.ui.measTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                self.ui.actTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                self.ui.stateTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                self.ui.fMatrixTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                self.ui.gMatrixTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                #self.ui.refOrbTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                #self.ui.actRefTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

        def centerCheckBox(self):
                #measurement check all  box centered
                self.ui.checkAllBoxGrid.setAlignment(Qt.AlignCenter)
                # this is Used to push the check all layout to the left
                self.ui.measSpacerGrid2.setAlignment(Qt.AlignCenter)
                self.ui.measSpacerGrid1.setAlignment(Qt.AlignCenter)
                self.ui.measSpacerGrid3.setAlignment(Qt.AlignCenter)
                self.ui.measSpacerGrid4.setAlignment(Qt.AlignCenter)
                self.ui.measSpacerGrid5.setAlignment(Qt.AlignCenter)
                #actuator check all  box centered
                self.ui.actCheckAllBoxGrid.setAlignment(Qt.AlignCenter)
                # this is Used to push the check all layout to the left
                self.ui.actSpacerGrid1.setAlignment(Qt.AlignCenter)
                self.ui.actSpacerGrid2.setAlignment(Qt.AlignCenter)
                self.ui.actSpacerGrid3.setAlignment(Qt.AlignCenter)
                self.ui.actSpacerGrid4.setAlignment(Qt.AlignCenter)
                self.ui.actSpacerGrid5.setAlignment(Qt.AlignCenter)

        def measItemChanged(self):
                # signal the user has changed the data and update the new data
                self.measItemChange = True
                num = self.ui.measTable.currentRow()
                try:
                        self.measDispArray[num] = float(self.ui.measTable.item(num,3).text())
                except:
                        print('enter number only')
                        self.ui.measTable.setItem(num,3,QTableWidgetItem(str(self.measDispArray[num])))
                try:
                        self.measHihiArray[num] = float(self.ui.measTable.item(num,5).text())
                except:
                        print('enter number only')
                        self.ui.measTable.setItem(num,5,QTableWidgetItem(str(self.measHihiArray[num])))
                try:
                        self.measLoloArray[num] = float(self.ui.measTable.item(num,4).text())
                except:
                        print('enter number only')
                        self.ui.measTable.setItem(num,4,QTableWidgetItem(str(self.measLoloArray[num])))

                self.ui.measTable.item(num,3).setTextAlignment(Qt.AlignCenter)
                self.ui.measTable.item(num,4).setTextAlignment(Qt.AlignCenter)
                self.ui.measTable.item(num,5).setTextAlignment(Qt.AlignCenter)
			
			

        def measRowHighlight(self):
                # signal which row has highlighted and store them inside an array of 1 (highlighted) and 0 (not highlighted)
                rowNum = self.ui.measTable.currentRow()
                if self.measTableHighlightArray[rowNum] == 0:
                        self.measTableHighlightArray[rowNum] =1
                        return
                if self.measTableHighlightArray[rowNum] == 1:
                        self.measTableHighlightArray[rowNum] =0
                        return

        def actItemChanged(self):
                # signal the user has changed the data and update the new data
                self.actItemChange = True
                num = self.ui.actTable.currentRow()
                try:
                        self.actEnergyArray[num] = float(self.ui.actTable.item(num,5).text())
                except:
                        print('enter number only')
                        self.ui.actTable.setItem(num,5,QTableWidgetItem(str(self.actEnergyArray[num])))
                try:
                        self.actHihiArray[num] = float(self.ui.actTable.item(num,4).text())
                except:
                        print('enter number only')
                        self.ui.actTable.setItem(num,4,QTableWidgetItem(str(self.actHihiArray[num])))
                try:
                        self.actLoloArray[num] = float(self.ui.actTable.item(num,3).text())
                except:
                        print('enter number only')
                        self.ui.actTable.setItem(num,3,QTableWidgetItem(str(self.actLoloArray[num])))
                self.ui.actTable.item(num,3).setTextAlignment(Qt.AlignCenter)
                self.ui.actTable.item(num,4).setTextAlignment(Qt.AlignCenter)
                self.ui.actTable.item(num,5).setTextAlignment(Qt.AlignCenter)
			

        def actRowHighlight(self):
                # signal which row has highlighted and store them inside an array of 1 (highlighted) and 0 (not highlighted)
                rowNum = self.ui.actTable.currentRow()
                if self.actTableHighlightArray[rowNum] == 0:
                        self.actTableHighlightArray[rowNum] =1
                        return
                if self.actTableHighlightArray[rowNum] == 1:
                        self.actTableHighlightArray[rowNum] =0
                        return

        def stateItemChanged(self):
                # signal the user has changed the data and update the new data
                self.stateItemChange = True
                num = self.ui.stateTable.currentRow()
                try:
                        self.stateSetPointArray[num] = float(self.ui.stateTable.item(num,2).text())
                except:
                        print('enter number only')
                        self.ui.stateTable.setItem(num,2,QTableWidgetItem(str(self.stateSetPointArray[num])))
                try:
                        self.stateHihiArray[num] = float(self.ui.stateTable.item(num,4).text())
                except:
                        print('enter number only')
                        self.ui.stateTable.setItem(num,4,QTableWidgetItem(str(self.stateHihiArray[num])))
                try:
                        self.stateLoloArray[num] = float(self.ui.stateTable.item(num,3).text())
                except:
                        print('enter number only')
                        self.ui.stateTable.setItem(num,3,QTableWidgetItem(str(self.stateLoloArray[num])))
                self.ui.stateTable.item(num,3).setTextAlignment(Qt.AlignCenter)
                self.ui.stateTable.item(num,4).setTextAlignment(Qt.AlignCenter)
                self.ui.stateTable.item(num,2).setTextAlignment(Qt.AlignCenter)

        def fMatrixItemChanged(self):
                # signal the changes in f matrix table and update the new data in a single array
                tempColumnNum = self.ui.fMatrixTable.currentColumn()
                tempRowNum = self.ui.fMatrixTable.currentRow()
                if tempColumnNum != -1 and tempRowNum != -1:
                        self.fMatrixItemChange = True
                        try:
                                self.fMatrixData[tempRowNum*5 + tempColumnNum-1] = float(self.ui.fMatrixTable.item(tempRowNum,tempColumnNum).text())
                        except:
                                print('enter number only')
                                self.ui.fMatrixTable.setItem(tempRowNum,tempColumnNum,QTableWidgetItem(str(round(self.fMatrixData[tempRowNum*5 + tempColumnNum-1],3))))
                                self.ui.fMatrixTable.item(tempRowNum,tempColumnNum).setTextAlignment(Qt.AlignCenter)

        def gMatrixItemChanged(self):
                # signal the changes in g matrix table and update the new data in a single array
                tempColumnNum = self.ui.gMatrixTable.currentColumn()
                tempRowNum = self.ui.gMatrixTable.currentRow()
                if tempColumnNum != -1 and tempRowNum != -1:
                        self.gMatrixItemChange = True
                        try:
                                self.gMatrixWinData[len(self.gMatrixTopCheckArray)*(tempRowNum-1)+(tempColumnNum-1)] = float(self.ui.gMatrixTable.item(tempRowNum,tempColumnNum).text())
                        except:
                                print('enter number only')
                                self.ui.gMatrixTable.setItem(tempRowNum,tempColumnNum,QTableWidgetItem(str(round(self.gMatrixWinData[len(self.gMatrixTopCheckArray)*(tempRowNum-1)+(tempColumnNum-1)],3))))

        def refOrbItemChanged(self):
                # signal the changes in ref orb table and update the every other column data
                tempColumnNum = self.ui.refOrbTable.currentColumn()
                tempRowNum = self.ui.refOrbTable.currentRow()
                if tempColumnNum != -1 and tempRowNum != -1:
                        self.refOrbItemChange = True
                        try:		
                                self.refOrbArray[tempRowNum*4+ tempColumnNum/2] = float(self.ui.refOrbTable.item(tempRowNum,tempColumnNum).text())
                        except:
                                print('enter number only')
                                self.ui.refOrbTable.setItem(tempRowNum,tempColumnNum,QTableWidgetItem(str(round(self.refOrbArray[tempRowNum*4+ tempColumnNum/2],6))))
				

        def actRefItemChanged(self):
                # signal the changes in act ref table and update the every other column data
                tempColumnNum = self.ui.actRefTable.currentColumn()
                tempRowNum = self.ui.actRefTable.currentRow()
                if tempColumnNum != -1 and tempRowNum != -1:
                        self.actRefItemChange = True
                        try:		
                                self.actRefArray[tempRowNum*2+ tempColumnNum/2] = float(self.ui.actRefTable.item(tempRowNum,tempColumnNum).text())
                        except:
                                print('enter number only')
                                self.ui.actRefTable.setItem(tempRowNum,tempColumnNum,QTableWidgetItem(str(round(self.actRefArray[tempRowNum*2+ tempColumnNum/2],6))))

        def measCamodeBoxChange(self):
                # signal the changes in measurement camode check boxes
                self.measItemChange = True

        def actCamodeBoxChange(self):
                # signal the changes in actuator camode check boxes
                self.actItemChange = True

        def doubleStateChange(self):
        # devnames ending with :X is checked  :Y has to be checked too
                self.measItemChange = True
                self.fMatrixFirstTime = False
                self.fMatrixItemChange = True
                for n in range(0,self.measurement.arraysize):
                        if self.measUsedBox[n] == self.sender():
                                positionNum = n
                tempName = self.measDevNameArray[positionNum]
                tempYname = tempName[:len(tempName)-1] + 'Y'
                tempXname = tempName[:len(tempName)-1] + 'X'
                for n in range (0,self.measurement.arraysize):
                        if tempYname == self.measDevNameArray[n]:
                                tempPositionNum = n
                        if tempXname == self.measDevNameArray[n]:
                                tempPositionNum1 = n
                self.measUsedBox[tempPositionNum].setChecked(self.measUsedBox[positionNum].checkState())
                self.measUsedBox[tempPositionNum1].setChecked(self.measUsedBox[positionNum].checkState())
				

        def gMatrixChange(self):
                # select or unselect used boxes in actuator and state table triggers changes in g matrix table
                self.gMatrixFirstTime = False
                self.gMatrixItemChange = True


        def matrixWindowRefresh(self):
                # when a row or column is unchecked, the table 'remove' (hide) the entire row or column.
                #================================== F matrix ====================================================================================
                self.ui.fMatrixTable.setRowCount(self.measurement.arraysize)
                self.tempColumn = 0     # n for loop through the arrays
                for n in range(0, self.measurement.arraysize):
                        # store checkboxes states into array of 1 (check) and 0 (uncheck)
                        if self.measUsedBox[n].checkState() == 2:
                                self.fMatrixCheckArray[n]= 1
                        else:
                                self.fMatrixCheckArray[n]= 0
                                # boxes checked rows - adding the devnames to the table
                        self.ui.fMatrixTable.setItem(n,0,QTableWidgetItem(self.fMatrixNameArray[n]))

                        self.ui.fMatrixTable.item(n,0).setFlags(QtCore.Qt.ItemIsEnabled)

                # remove unchecked rows from measurement table
                self.tempCurrentRow = 0
                for n in range(0,self.measurement.arraysize):
                        if self.fMatrixCheckArray[n] == 1:
                                self.tempCurrentRow = self.tempCurrentRow + 1
                        else:
                                self.ui.fMatrixTable.removeRow(self.tempCurrentRow)

                if self.fMatrixFirstTime == False: # measurement checkboxes changed
                        # ======================================= use AIDA =================================================
                        self.fMatrixData = AIDA
                        if  self.launchName != "UndulatorLaunch":
		                # ======================================= use matlab =================================================
				#self.fMatrixData = matlabpolynomial
                                self.fMatrixItemChange =True

							#self.fMatrixItemChange =True
                        # ====================================================================================================

                        self.fMatrixItemChange =True
                else:
		            # add all data to all rows
                        for n in range(0,self.measurement.arraysize):
                                self.ui.fMatrixTable.setItem(n,1,QTableWidgetItem(str(round(self.fMatrixData[(n*5)],3))))
                                self.ui.fMatrixTable.setItem(n,2,QTableWidgetItem(str(round(self.fMatrixData[(n*5)+1],3))))
                                self.ui.fMatrixTable.setItem(n,3,QTableWidgetItem(str(round(self.fMatrixData[(n*5)+2],3))))
                                self.ui.fMatrixTable.setItem(n,4,QTableWidgetItem(str(round(self.fMatrixData[(n*5)+3],3))))
                                self.ui.fMatrixTable.setItem(n,5,QTableWidgetItem(str(round(self.fMatrixData[(n*5)+4],3))))

                # format, center widgets
                for n in range(0,self.fMatrixCheckArray.count(1)):
                        for j in range (0,6):
                                self.ui.fMatrixTable.item(n,j).setTextAlignment(Qt.AlignCenter)

                #=====================================================================================================================================



                #====================================== G matrix ===========================================================================================
                # row and column length based on how many boxes are checked
                self.ui.gMatrixTable.setColumnCount(len(self.gMatrixTopCheckArray)+1)
                self.ui.gMatrixTable.setRowCount(len(self.gMatrixLeftCheckArray)+1)
                for n in range(0,self.state.arraysize):
                        # store boxes state into array of 1 (checked) and 0 (uncheck) for both States and Actuators
                        if self.stateUsedBox[n].checkState() == 2:
                                self.gMatrixLeftCheckArray[n]=1
                        else :
                                self.gMatrixLeftCheckArray[n]=0
                for n in range(0,self.actuator.arraysize):
                        if self.actUsedBox[n].checkState() == 2:
                                self.gMatrixTopCheckArray[n]=1
                        else :
                                self.gMatrixTopCheckArray[n]=0

                # add state name to table
                for n in range(0,self.state.arraysize):
                        self.ui.gMatrixTable.setItem(n+1 ,0,QTableWidgetItem(self.gMatrixLeftDevNameArray[n]))
                        self.ui.gMatrixTable.item(n+1,0).setFlags(QtCore.Qt.ItemIsEnabled)

                # add actuatos name to table, no ending attributes or (units)    EX: XCOR:IN20:381 is shown instead of XCOR:IN2:381:BCTRL(kG-m)
                x = self.gMatrixTopNameArray[0].rfind(":")
                for n in range(0,len(self.gMatrixTopCheckArray)) :
                        x = self.gMatrixTopNameArray[n].rfind(":")
                        if x != -1:
                                self.ui.gMatrixTable.setItem(0,n+1,QTableWidgetItem(str(self.gMatrixTopNameArray[n][:x])))
                        else :
                                self.ui.gMatrixTable.setItem(0,n+1,QTableWidgetItem(str(self.gMatrixTopNameArray[n])))
                        self.ui.gMatrixTable.item(0,n+1).setFlags(QtCore.Qt.ItemIsEnabled)

                if self.gMatrixFirstTime == False:
                        # ========================= use AIDA =========================================
                        """
						self.gMatrixWinData = AIDA



                        """
                        self.gMatrixItemChange =True
                        # ====================================================================================================

                # adding g matrix data to the table. x to loop through data array and  n j loop through row and column
                else:
                        x = 0
                        for n in range(0,self.state.arraysize):
                                for j in range(0, len(self.gMatrixTopCheckArray)):
                                        self.ui.gMatrixTable.setItem(n+1,j+1,QTableWidgetItem(str(round(self.gMatrixWinData[x],3))))
                                        x = x + 1


                # add text 'name' at position 0,0
                self.ui.gMatrixTable.setItem(0,0,QTableWidgetItem('Name'))
                self.ui.gMatrixTable.item(0,0).setFlags(QtCore.Qt.ItemIsEnabled)

                # delete row and column when needed.
                # currentColumn and currentRow used to keep track of which row or column to remove.
                self.currentColumn = 1
                self.currentRow = 1
                for n in range(0, self.actuator.arraysize):
                        if self.gMatrixTopCheckArray[n] == 1:
                                self.currentColumn = self.currentColumn + 1
                        else:
                                self.ui.gMatrixTable.removeColumn(self.currentColumn)
                for n in range(0, self.state.arraysize):
                        if self.gMatrixLeftCheckArray[n] == 1:
                                self.currentRow = self.currentRow + 1
                        else:
                                self.ui.gMatrixTable.removeRow(self.currentRow)


        def refOrbWindowRefresh(self):
                #  add data to every other column in ref orb table, 8 columns
                row = 0
                column = 0
                for n in range(0, len(self.refOrbArray)):
                        self.ui.refOrbTable.setItem(row, column, QTableWidgetItem(self.refOrbNameArray[n]))
                        self.ui.refOrbTable.item(row,column).setFlags(QtCore.Qt.ItemIsEnabled)

                        self.ui.refOrbTable.setItem(row,column+1,QTableWidgetItem(str(round(self.refOrbArray[n],6))))
                        column = column + 2
                        if column > 7 :
                                row = row + 1
                                column = 0

                # add data to every other column in act ref table, 4 columns
                row = 0
                column = 0
                for n in range(0,len(self.actRefArray)):
                        self.ui.actRefTable.setItem(row,column, QTableWidgetItem(self.actRefNameArray[n]))
                        self.ui.actRefTable.item(row,column).setFlags(QtCore.Qt.ItemIsEnabled)
                        self.ui.actRefTable.setItem(row,column +1 , QTableWidgetItem(str(round(self.actRefArray[n],6))))
                        column = column +2
                        if column > 3 :
                                row = row + 1
                                column = 0


        def importMatrix(self):
                # open the mat lab file based on user's choice, match the correct actuator names then update the corresponding data.
                # match feedback loop "actnames", update "FMatrix" data to f matrix table  and "CorrMatrix" to g matrix table
                try :
                        fMatrixName = QFileDialog.getOpenFileName(self,'import@' + os.environ['HOME'],self.matLink,"Matlab Files(*.mat)")
                        fileName = fMatrixName[0][fMatrixName[0].rfind('/')+1:]
                        matrixFile = loadmat(self.matLink + str(fileName))
                        actNames = matrixFile['actNames']       # get the actuatorNames from matlab file
                        tempActNames = []
                        x = self.gMatrixTopNameArray[0].rfind(":")      # get the actNames from PV without X or Y ending
                        for n in range(0,len(self.gMatrixTopNameArray)) :
                                x = self.gMatrixTopNameArray[n].rfind(":")
                                if x != -1 :
                                        tempActNames.append(str(self.gMatrixTopNameArray[n][:x]))
                                else :
                                        tempActNames.append(str(self.gMatrixTopNameArray[n]))

                        if self.sender() == self.ui.importFbutton:
                                try:
                                        FMatrix = matrixFile['FMatrix']         # check if there is FMatrix data in matlab file
                                        if (actNames == tempActNames).all():    # check for matching actuator names
                                                self.fMatrixData = FMatrix      # match => f matrix = matlab file f matrix data
                                                self.fMatrixData = self.fMatrixData.ravel()
                                                self.fMatrixItemChange = True
                                except:
                                        print('No F Matrix Data')
                                self.matrixWindowRefresh()      # refresh the window the print new data

                        if self.sender() == self.ui.importGbutton:
                                try :
                                        corrMatrix = matrixFile['CorrMatrix']   # check if there is GMatrix data in matlab file
                                        tempData = []
                                        if (actNames == tempActNames).all():    # check for matching actuator names
                                                self.gMatrixWinData = corrMatrix        # match => g matrix = matlab file g matrix data
                                                self.gMatrixWinData = self.gMatrixWinData.ravel()
                                                self.gMatrixItemChange = True


                                                # original PV data. horizontal format , delete both print statements to see the difference
                                                #print(self.gMatrixWinData)
                                                for j in range (0, len(self.gMatrixLeftCheckArray)):
                                                        for n in range(0,len(self.gMatrixTopCheckArray)):
                                                                tempData.append(self.gMatrixWinData[n*4+j])
                                                self.gMatrixWinData = tempData
                                                # new data, vertical format, fit the matrix table.
                                                #print(self.gMatrixWinData)


                                except :
                                        print('No CorrMatrix Data')
                                self.matrixWindowRefresh()      # refresh the window the print new data

                except :
                        print("can't open the file")

        def fMatrixGetData(self):
                # check for undulator launch, use polynomials.  ex : FBCK:FB03:TR04:NAME
                #if self.launchName == "UndulatorLaunch":
                # ========= use MATLAB Control to calculate polynomials
                #
                #else:
                # ======== get from AIDA/ MODEL DB ====================


                #self.fMatrixItemChange = True
                return






        # switching screens
        def changePage1(self):
                self.ui.actButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.measButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.page.setCurrentIndex(0)

        def changePage2(self):
                self.ui.measButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.actButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.page.setCurrentIndex(2)

        def changePage3(self):
                self.ui.actButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.measButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.page.setCurrentIndex(1)

        def changePage4(self):
                #  called twice to avoid a bug
                self.matrixWindowRefresh()
                self.matrixWindowRefresh()
                self.ui.actButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.measButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.page.setCurrentIndex(3)

        def changePage5(self):
                self.refOrbWindowRefresh()
                self.ui.actButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.measButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.timeButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.page.setCurrentIndex(5)

        def changePage6(self):
                self.ui.actButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.measButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.stateButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.matrixButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.refOrbButton.setStyleSheet("background-color: rgb(255,255,255)")
                self.ui.timeButton.setStyleSheet("background-color: rgb(150,255,255)")
                self.ui.page.setCurrentIndex(4)



        def ui_filename(self):
                return 'feedbackloop.ui'

        def ui_filepath(self):
                return path.join(path.dirname(path.realpath(__file__)), self.ui_filename())

