def __init__(self, loop=None):
        super().__init__()
        QWeatherStationIP = "tcp://10.90.61.231:5559"
        name = 'OscilloscopeGuiSR'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,
                                     name=name,
                                     loop=self.loop)
        self.setWindowTitle('Oscilloscopes')
        self.setFont(QtGui.QFont('Helvetica', 12))
        self.initialize_osc()
        self.initialize_GUI()
        self.restore_GUI()
        logging.getLogger().addHandler(self.logbox)
        logging.getLogger('asyncio').addHandler(self.logbox)
        logging.getLogger().setLevel(logging.DEBUG)
        logging.getLogger('asyncio').setLevel(logging.DEBUG)
        self.logbox.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s',
                              "%H:%M:%S"))
        self.PROCESS = psutil.Process(os.getpid())

        self.loop.create_task(self.client.run())
Esempio n. 2
0
    def __init__(self, loop):
        super().__init__()

        self.setWindowTitle('Test GUI')

        self.initialize()
        brokerconn = "tcp://localhost:5559"
        self.client = QWeatherClient(brokerconn, loop=loop, name='testgui')
        self.client.subscribe('ServerA', self.print_message)
        self.loop = loop
        self.loop.create_task(self.client.run())
 def __init__(self, loop=None):
     super().__init__()
     QWeatherStationIP = "tcp://10.90.61.231:5559"
     name = 'Sr1Gui'
     if loop is None:
         self.loop = asyncio.get_event_loop()
     else:
         self.loop = loop
     self.client = QWeatherClient(QWeatherStationIP,
                                  name=name,
                                  loop=self.loop)
     self.Srbrain = self.client.StrontiumBrain
     self.setWindowTitle('Strontium Pulse GUI')
     self.setFont(QtGui.QFont('Helvetica', 12))
     self.initialize_GUI()
     self.loop.create_task(self.client.run())
    def __init__(self,loop = None):
        super().__init__()
        QWeatherStationIP = "tcp://172.24.19.74:5559"
        name = 'AD9959GUI'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,name=name,loop=self.loop)
        try:
            self.server = self.client.AD9959
        except Exception as e:
            print(e,'could not find server')
        self.setWindowTitle('AD9959')
        self.setFont(QtGui.QFont('Helvetica',16))

        self.initialize()
        self.restoreGUI()
        self.loop.create_task(self.client.run())
    def __init__(self, loop=None):
        super().__init__()
        QWeatherStationIP = "tcp://10.90.61.231:5559"
        name = 'CameraGUI'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,
                                     name=name,
                                     loop=self.loop)
        self.camprocess = None
        self.SrBrainprocess = None

        self.setWindowTitle('BlackFly Camera GUI')
        self.setFont(QtGui.QFont('Helvetica', 12))
        self.initialize_GUI()
        self.restore_GUI()
        self.saving = False
        self.loop.create_task(self.client.run())
Esempio n. 6
0
class testgui(QWidget):
    def __init__(self, loop):
        super().__init__()

        self.setWindowTitle('Test GUI')

        self.initialize()
        brokerconn = "tcp://localhost:5559"
        self.client = QWeatherClient(brokerconn, loop=loop, name='testgui')
        self.client.subscribe('ServerA', self.print_message)
        self.loop = loop
        self.loop.create_task(self.client.run())

    def initialize(self):
        sendbutton = QPushButton('Send command to server 1')
        l1 = QLabel()
        l2 = QLabel()
        sendbutton2 = QPushButton('Send command to server 2')
        layout = QVBoxLayout()
        layout.addWidget(sendbutton)
        layout.addWidget(l1)
        layout.addWidget(sendbutton2)
        layout.addWidget(l2)

        sendbutton.pressed.connect(lambda: self.loop.create_task(
            self.send_command(self.client.ServerA.do_something_scheduled())))
        sendbutton2.pressed.connect(lambda: self.loop.create_task(
            self.send_command(self.client.ServerB.get_number())))
        self.setLayout(layout)
        self.show()

    def print_message(self, msg):
        print('msg> ', msg)

    async def send_command(self, func):
        a = await func
        print(a)

    def closeEvent(self, e):
        self.loop.stop()
class AD9959Gui(QWidget):

    def __init__(self,loop = None):
        super().__init__()
        QWeatherStationIP = "tcp://172.24.19.74:5559"
        name = 'AD9959GUI'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,name=name,loop=self.loop)
        try:
            self.server = self.client.AD9959
        except Exception as e:
            print(e,'could not find server')
        self.setWindowTitle('AD9959')
        self.setFont(QtGui.QFont('Helvetica',16))

        self.initialize()
        self.restoreGUI()
        self.loop.create_task(self.client.run())

    def initialize(self):
        titlelabel = QLabel(self.server.name)
        titlelabel.setFont(QtGui.QFont('Helvetica',20,75))
        channelpattern = self.make_channel_panel()
        frequencyPanel = self.make_frequency_panel()
        amppanel = self.make_amp_panel()
        phasepanel = self.make_phase_panel()
        layout = QVBoxLayout()

        layout.addWidget(titlelabel)
        layout.addWidget(channelpattern)
        layout.addWidget(frequencyPanel)
        layout.addWidget(amppanel)
        layout.addWidget(phasepanel)

        self.setLayout(layout)
        self.show()

    def make_channel_panel(self):
        panel = QFrame()
        buttonnames = ['1','2','3','4','All']
        buttonlist = [QRadioButton() for alabel in buttonnames]
        labellist = [QLabel(alabel) for alabel in buttonnames]
        self.channeldata = [[0,0,0,None,None,None] for abutton in buttonlist ]
        titlelabel = QLabel('Channel')
        titlelabel.setAlignment(QtCore.Qt.AlignCenter)
        font = titlelabel.font()
        font.setBold(True)
        titlelabel.setFont(font)
        layout = QGridLayout()
        layout.addWidget(titlelabel,0,0,1,len(buttonlist),QtCore.Qt.AlignHCenter)
        for ind,(abut,alab) in enumerate(zip(buttonlist,labellist)):
            layout.addWidget(alab,1,ind,QtCore.Qt.AlignHCenter)
            layout.addWidget(abut,2,ind,QtCore.Qt.AlignHCenter)
            abut.clicked.connect(lambda state,x=ind: self.set_channel(x) if state else None)

        buttonlist[0].click()


        panel.setLayout(layout)
        panel.setFrameStyle(0x00001)
        return panel

    def set_channel(self,channel):
        if channel == 5:
            self.currentchannel = -1 ## Because the dds code is written sich that -1 is all channels.
        else:
            self.currentchannel = channel
            try:
                freq,amp,phase,freqbox,ampbox,phasebox = self.channeldata[self.currentchannel-1]
                freqbox.setValue(freq)
                ampbox.setValue(amp)
                phasebox.setValue(phase)
                for abox in [freqbox,ampbox,phasebox]:
                    abox.editingFinished.emit()
            except AttributeError as e:
                pass

    def make_frequency_panel(self):
        panel = QFrame()
        freqbox = QDoubleSpinBox()
        freqbox.setRange(0.1,500)
        freqbox.setSingleStep(1)
        freqbox.setDecimals(6)
        freqbox.setSuffix(' MHz')
        freqbox.setObjectName('FreqBox')
        resbox = QComboBox()
        resbox.addItems(['MHz','KHz','Hz','mHz','uHz'])


        freqlabel = QLabel('#### MHz')
        titlelabel = QLabel('Frequency')
        font = titlelabel.font()
        font.setBold(True)
        titlelabel.setFont(font) 
        for achan in self.channeldata:
            achan[3] = freqbox

        def freqedited(freq):
            self.server.setFrequency(self.currentchannel,freq)
            freqlabel.setText('{:.6f} MHz'.format(freq))
            self.channeldata[self.currentchannel-1][0] = freq

        resbox.currentIndexChanged.connect(lambda ind: freqbox.setSingleStep(10**(-ind*3)))
        freqbox.editingFinished.connect(lambda :freqedited(freqbox.value()))
        freqbox.valueChanged.connect(lambda :freqbox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)


     

        layout = QGridLayout()
        layout.addWidget(titlelabel,0,0)
        layout.addWidget(freqbox,1,0)
        layout.addWidget(resbox,0,1)
        layout.addWidget(freqlabel,1,1,QtCore.Qt.AlignRight)
        panel.setLayout(layout)
        return panel


    def make_amp_panel(self):
        panel = QFrame()
        ampbox = QDoubleSpinBox()
        ampbox.setRange(0.1,30)
        ampbox.setSingleStep(0.1)
        ampbox.setDecimals(1)
        ampbox.setSuffix(' dBm')
        ampbox.setObjectName('AmpBox')


        amplabel = QLabel('#### dBm')
        titlelabel = QLabel('Amplitude')
        font = titlelabel.font()
        font.setBold(True)
        titlelabel.setFont(font) 

        for achan in self.channeldata:
            achan[4] = ampbox

        def ampedited(amp):
            self.server.setAmplitude(self.currentchannel,amp)
            amplabel.setText('{:.6f} MHz'.format(amp))
            self.channeldata[self.currentchannel-1][1] = amp


        ampbox.editingFinished.connect(lambda :ampedited(ampbox.value()))
        ampbox.valueChanged.connect(lambda :ampbox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)


        layout = QGridLayout()
        layout.addWidget(titlelabel,0,0)
        layout.addWidget(ampbox,1,0)
        layout.addWidget(amplabel,1,1,QtCore.Qt.AlignRight)
        panel.setLayout(layout)
        return panel

    def make_phase_panel(self):
        panel = QFrame()
        phasebox = QDoubleSpinBox()
        phasebox.setRange(0,360)
        phasebox.setSingleStep(0.1)
        phasebox.setDecimals(1)
        phasebox.setSuffix(' degrees')
        phasebox.setObjectName('PhaseBox')

#        resbox.set_

        phaselabel = QLabel('#### Degrees')
        titlelabel = QLabel('Phase')
        font = titlelabel.font()
        font.setBold(True)
        titlelabel.setFont(font) 

        for achan in self.channeldata:
            achan[5] = phasebox


        def phaseedited(phase):
            self.server.setPhase(self.currentchannel,phase)
            phaselabel.setText('{:.6f} MHz'.format(phase))
            self.channeldata[self.currentchannel-1][2] = phase

        phasebox.editingFinished.connect(lambda :phaseedited(phasebox.value()))
        phasebox.valueChanged.connect(lambda :phasebox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)


        layout = QGridLayout()
        layout.addWidget(titlelabel,0,0)
        layout.addWidget(phasebox,1,0)
        layout.addWidget(phaselabel,1,1,QtCore.Qt.AlignRight)
        panel.setLayout(layout)
        return panel

    def restoreGUI(self):
        settings = QtCore.QSettings(self.server.name+'_gui.ini',QtCore.QSettings.IniFormat)

        for aspinbox in self.findChildren(QDoubleSpinBox) + self.findChildren(QSpinBox):
            name = aspinbox.objectName()
            if settings.contains(name):
                value = settings.value(name,type=float)
                aspinbox.setValue(value)


            for i in range(len(self.channeldata)):
                name = 'channel{:d}'.format(i+1)
                if settings.contains(name):
                    value = settings.value(name,type=float)
                    self.channeldata[i][0] = value[0]
                    self.channeldata[i][1] = value[1]
                    self.channeldata[i][2] = value[2]



    def closeEvent(self,e):
        settings = QtCore.QSettings(self.server.name+'_gui.ini',QtCore.QSettings.IniFormat)

        for aspinbox in self.findChildren(QDoubleSpinBox) + self.findChildren(QSpinBox):
            name = aspinbox.objectName()
            value = aspinbox.value()
            settings.setValue(name,value)
        for i in range(len(self.channeldata)):
            settings.setValue('channel{:d}'.format(i+1),self.channeldata[i][:3])

        settings.sync()
        self.loop.stop()
class CamGui(QWidget):

    def __init__(self,loop = None):
        super().__init__()
        QWeatherStationIP = "tcp://10.90.61.231:5559"
        name = 'CameraGUI'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,name=name,loop=self.loop)
        self.camera = self.client.BlackflyCamera
        self.Srbrain = self.client.StrontiumBrain
        self.setWindowTitle('BlackFly Camera GUI')
        self.setFont(QtGui.QFont('Helvetica',12))
        self.initialize_GUI()
        self.restore_GUI()
        self.saving = False
        self.loop.create_task(self.client.run())

    def initialize_GUI(self):
        self.resultarray = []
        imagepanel = self.make_imagepanel()
        settingspanel = self.make_settingspanel()
        self.Srbrainpanel = SrBrainGui()#self.make_SRbrainpanel()
        self.Srbrain = self.Srbrainpanel.Srbrain
        buttonpanel = self.make_buttonspanel()
        self.Temp = self.make_temppanel()
        
        tabwig = QTabWidget()
        tabwig.addTab(settingspanel,'Settings')
        tabwig.addTab(self.Srbrainpanel,'Timings')

        layout = QGridLayout()
        layout.addWidget(imagepanel,0,0)

        layout.addWidget(tabwig,1,0)
        layout.addWidget(buttonpanel,2,0)
        self.setLayout(layout)

        self.show()
        print('MT: initialized')

    async def grab_image(self,stop):
        print('grabbing')
        while not stop.is_set():
            image = await self.camera.getImage()
            if image is None:
                print('None')
                pass
            else:
                self.update_images(image)

        print('stopped grabbing')


    async def get_single_image(self,sender):
        self.camera.acquisitionMode('single')
        image = await self.camera.acquireSingleImage()
        thisimage=QtGui.QImage(image,1920,1200,1920,QtGui.QImage.Format_Grayscale8)
        self.update_images(thisimage)

    async def log_images(self,stop):
        while not stop.is_set():
            asyncio.sleep(10)
            self.datavault.saveData(self.resultarray[-1])
            self.resultarray = []

    async def gather_images(self,stop):
        while not stop.is_set():
            asyncio.sleep(1)
            if len(self.resultarray)>= 10:
                pass



    def log_clicked(self,state):
        self.resultarray = []
        self.saving = True


        return
        if state:
            logpath = 'Z:\Sr1\MOT Image Logging'
            self.sender().setText('Logging 1 picture every 10 s')
            date = datetime.datetime.now().strftime('%Y%m%d')
            self.savelocation = logpath + '/' + date
            if not os.path.exists(self.savelocation):
                os.mkdir(self.savelocation)
            self.savelocation += '/'
            self.datavault = self.client.DataVault
            self.stoplog = asyncio.Event()
            self.loop.create_task(self.log_images(self.stoplog))
        if not state:
            self.sender().setText('Press to log (1 every 10s)')
            self.stoplog.set()



    def wait_for_trigger_clicked(self,state):
        if state:
            self.imagehistoryarray = []
            self.sender().setText('Waiting for trigger (press to abort)')
            self.camera.acquisitionMode('cont')
            self.camera.triggerMode('on')
            self.camera.triggerSource('hardware')
            #or abutton in self.autobuttonlist:
            #    abutton.toggle() #sets all the auto values off
            self.stopcont = asyncio.Event()
            self.camera.beginAcquisition()
            self.loop.create_task(self.grab_image(self.stopcont))
        if not state:
            self.sender().setText('Wait for trigger')
            self.camera.endAcquisition()
            self.camera.triggerMode('off')
            self.stopcont.set()

    def update_images(self,image):
        image = image.astype(float)
        image = image.reshape(self.expectedPixels[1],self.expectedPixels[0])
        image = np.transpose(image)
        print(len(self.imagehistoryarray))
        if len(self.imagehistoryarray) > 1:
            self.imagehistoryarray = []
        self.imagehistoryarray.insert(0,image)
        if len(self.imagehistoryarray) == 2:
            diffim = (self.imagehistoryarray[0]-self.imagehistoryarray[1])
            self.mainImage.setImage(diffim)
            smallim1 = self.imagehistoryarray[0]
            smallim2 = self.imagehistoryarray[1]
            for i, anim in enumerate([smallim1,smallim2]):
                self.imagehistorycontainer[i].setImage(anim)
            self.update_histogram(diffim)
            if self.saving:
                self.resultarray.append(self.ROI.getArrayRegion(diffim,self.mainImage))
            if len(self.resultarray) == 10:
                self.waitbutton.toggle()
                for i,anim in enumerate(self.resultarray):
                    np.savetxt('testpic{:d}.csv'.format(i), anim, delimiter=",")
                self.saving = False
                self.resultarray = []

    def update_histogram(self,diffimage):
        ROIimage = self.ROI.getArrayRegion(diffimage,self.mainImage)
        coords = self.ROI.parentBounds()
        xsize = np.size(ROIimage,0)
        ysize = np.size(ROIimage,1)
        try:
            xdata = ROIimage[:,int(ysize/2+0.5)]
            ydata = ROIimage[int(xsize/2+0.5),:]

            self.histogramplot[0].setData(x = list(range(0,xsize)), y = xdata) #red
            self.histogramplot[1].setData(x = list(range(0,ysize)), y = ydata) #green

            self.xline.setData(x = [coords.x(),coords.x()+coords.width()],y = [coords.y()+coords.height()/2, coords.y()+coords.height()/2]) #red
            
            self.yline.setData(x = [coords.x()+coords.width()/2, coords.x()+coords.width()/2],y = [coords.y(),coords.y()+coords.height()]) #green
        except Exception as e:
            print(e)



    def make_imagepanel(self):
        self.expectedPixels = (1920,1200)
        panel = QFrame()
        panel.setFrameStyle(QFrame.Raised | QFrame.Panel)
        MainPwig = pg.PlotWidget()

        # Get the colormap
        colormap = cm.get_cmap("nipy_spectral")  # cm.get_cmap("CMRmap")
        colormap._init()
        lut = (colormap._lut * 255).view(np.ndarray)  # Convert matplotlib colormap from 0-1 to 0 -255 for Qt

        self.mainImage = pg.ImageItem()
        self.mainImage.setLookupTable(lut)
        MainPwig.addItem(self.mainImage)
        MainPwig.setMaximumSize(640,400)
        sp = MainPwig.sizePolicy()
        sp.setHorizontalPolicy(QSizePolicy.Fixed)
        sp.setVerticalPolicy(QSizePolicy.Fixed)
        MainPwig.setSizePolicy( sp )

        layout = QGridLayout()

        self.imagehistorycontainer = [pg.ImageItem() for i in range(2)]#[QLabel() for i in range(3)]
        for animage in self.imagehistorycontainer:
            animage.setLookupTable(lut)

        self.imagehistoryarray = [None,None,None,None]
        for i,awidget in enumerate([pg.PlotWidget() for i in range(2)]):     
            awidget.setMaximumSize(213,133)
            sp = awidget.sizePolicy()
            sp.setHorizontalPolicy(QSizePolicy.Fixed)#setHeightForWidth( True)
            sp.setVerticalPolicy(QSizePolicy.Fixed)
            awidget.setSizePolicy( sp )
            awidget.addItem(self.imagehistorycontainer[i])
            layout.addWidget(awidget,i+1,4)



        #Histogramplot

        histplot = pg.PlotWidget()
        self.histogramplot = [histplot.plot(),histplot.plot()]
        self.histogramplot[0].setPen((255,0,0))
        self.histogramplot[1].setPen((0,255,0))
        self.xline = MainPwig.plot()
        self.yline = MainPwig.plot()
        self.xline.setPen((255,0,0))
        self.yline.setPen((0,255,0))


        #Region of interest
        self.ROI = pg.ROI([100,100], [400,400])
        MainPwig.addItem(self.ROI)
        ## handles scaling horizontally around center
        self.ROI.addScaleHandle([1, 0.5], [0.5, 0.5])
        self.ROI.addScaleHandle([0, 0.5], [0.5, 0.5])

        ## handles scaling vertically from opposite edge
        self.ROI.addScaleHandle([0.5, 0], [0.5, 1])
        self.ROI.addScaleHandle([0.5, 1], [0.5, 0])

        ## handles scaling both vertically and horizontally
        self.ROI.addScaleHandle([1, 1], [0, 0])
        self.ROI.addScaleHandle([0, 0], [1, 1])




        layout.addWidget(histplot,3,4)


        layout.addWidget(QLabel('Current image'),0,1)
        layout.addWidget(MainPwig,1,0,3,3)

        layout.addWidget(QLabel('NoMot'),1,5)
        layout.addWidget(QLabel('MOT'),2,5)
        layout.setAlignment(QtCore.Qt.AlignCenter)

        panel.setLayout(layout)
        return panel

    def make_buttonspanel(self):
        panel = QFrame()
        self.logbutton = QPushButton('Press to log (1 every 10s)')
        self.logbutton.setCheckable(True)
        self.waitbutton = QPushButton('Wait for Trigger')
        self.waitbutton.setCheckable(True)
        self.waitbutton.toggled.connect(self.wait_for_trigger_clicked)
        self.logbutton.clicked.connect(self.log_clicked)


        layout = QGridLayout()
        layout.addWidget(self.logbutton,0,0)
        layout.addWidget(self.waitbutton,0,2)

        panel.setLayout(layout)
        return panel

    def check_autobutton(self,state,box):
        name = self.sender().text().split()[1]

        if state:
            box.setReadOnly(True)
            box.setKeyboardTracking(False)
            if name == 'Exposure':
                self.camera.exposureAuto('on')
            elif name == 'Gain':
                self.camera.gainAuto('on')
            elif name == 'level':
                self.camera.BlacklevelAuto('on')
        else:
            box.setReadOnly(False)
            box.setKeyboardTracking(True)
            if name == 'Exposure':
                self.camera.exposureAuto('off')
                #await box.setValue(self.camera.exposure())
            elif name == 'Gain':
                self.camera.gainAuto('off')
                #box.setValue(self.camera.gain())
            elif name == 'Level':
                self.camera.blacklevelAuto('off')
                #box.setValue(self.camera.blacklevel())

    

    def change_bitmode(self,state):
        if state:
            self.sender().setText('12 bit')
            self.camera.bitFormat(12)
        else:
            self.sender().setText('8 bit')
            self.camera.bitFormat(8)


    def make_settingspanel(self):
        #Load current settings from the camera
        CamExp = self.camera.exposure()
        CamExpAuto = self.camera.exposureAuto()
        CamGain = self.camera.gain()
        CamGainAuto = self.camera.gainAuto()
        CamBlack = self.camera.blacklevel()
        #CamBlackAuto = self.camera.blacklevelAuto()
        CamBit = self.camera.bitFormat()
        CamBin = self.camera.binning()


        panel = QFrame()
        Expolabel = QLabel('Exposure Time')
        Expobox = QDoubleSpinBox()
        Expobox.setValue(CamExp/1000)
        Expobox.setDecimals(3)
        Expobox.setRange(0.019,3900)
        Expobox.setSuffix(' ms')
        ExpoAuto = QCheckBox('Auto Exposure')
        if CamExpAuto == 'on':
            ExpoAuto.setChecked(True)
        Gainlabel = QLabel('Gain Factor')
        Gainbox = QDoubleSpinBox()
        Gainbox.setSuffix(' dB')
        Gainbox.setDecimals(2)
        Gainbox.setRange(0.00,29.99)
        GainAuto = QCheckBox('Auto Gain')
        if CamGainAuto == 'on':
            GainAuto.setChecked(True)
        BlackLevellabel = QLabel('Black Level')
        BlackLevelbox = QSpinBox()
        BlackLevelbox.setRange(1,100)
        BlackLevelbox.setSuffix(' %')
        BlackLevelAuto = QCheckBox('Auto Black Level')
        #if CamBlackAuto == 'on':
         #   BlackLevelAuto.setChecked(True)

        bitBut = QPushButton('8 Bit')
        bitBut.setCheckable(True)
        if CamBit[0] == 'Mono8':
            bitBut.setChecked(False)
        bitBut.toggled.connect(self.change_bitmode)

        binDrop = QComboBox()
        binDrop.addItems(['No binning','2x2 binning','4x4 binning'])
        if CamBin == (2,2):
            binDrop.setCurrentIndex(1)
            self.expectedPixels = (960,600)
        elif CamBin == (4,4):
            binDrop.setCurrentIndex(2)
            self.expectedPixels = (480,300)

        binDrop.currentTextChanged.connect(self.change_binning)




        self.autobuttonlist = []
        for abut,abox in [(ExpoAuto,Expobox),(GainAuto,Gainbox),(BlackLevelAuto,BlackLevelbox)]:
            abox.setKeyboardTracking(False)
            abox.setReadOnly(True)
            abut.toggled.connect(lambda state,box = abox: self.check_autobutton(state,box))
            self.autobuttonlist.append(abut)

        Expobox.valueChanged.connect(lambda value: self.camera.exposure(value*1000))
        Expobox.valueChanged.connect(lambda :Expobox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)
        Gainbox.valueChanged.connect(self.camera.gain)
        Gainbox.valueChanged.connect(lambda :Gainbox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)
        BlackLevelbox.valueChanged.connect(self.camera.blacklevel)
        BlackLevelbox.valueChanged.connect(lambda :BlackLevelbox.lineEdit().deselect(), QtCore.Qt.QueuedConnection)

        layout = QGridLayout()
        layout.addWidget(Expolabel,      0,0)
        layout.addWidget(Expobox,        0,1)
        layout.addWidget(ExpoAuto,       0,2)
        layout.addWidget(Gainlabel,      1,0)
        layout.addWidget(Gainbox,        1,1)
        layout.addWidget(GainAuto,       1,2)
        layout.addWidget(BlackLevellabel,2,0)
        layout.addWidget(BlackLevelbox,  2,1)
        layout.addWidget(BlackLevelAuto, 2,2)
        layout.addWidget(bitBut,3,0)
        layout.addWidget(binDrop,3,1)

        panel.setLayout(layout)
        return panel

    def change_binning(self,text):
        if text == 'No binning':
            self.camera.binning((1,1))
            self.expectedPixels = (1920,1200)
        elif text == '2x2 binning':
            self.camera.binning((2,2))
            #self.camera.binningMode('Average')
            self.expectedPixels = (960,600)
        elif text == '4x4 binning':
            self.camera.binning((4,4))
            #self.camera.binningMode('Average')
            self.expectedPixels = (480,300)

    def make_temppanel(self):
        pass
#        TStart = mySpinbox()
#        TStop = mySpinbox()
#        dT = mySpinbox()
#        Toplayout = QGridLayout()
#        timings = QGridLayout()
#        timings.addWidget(QLabel('Start time (ms)'),0,0)
#        timings.addWidget(TStart,0,1)
#        timings.addWidget(QLabel('Stop time (ms)'),1,0)
#        timings.addWidget(TStop,1,1)
#        timings.addWidget(QLabel('timestep (ms)'),2,0)
#        timings.addWidget(dT,2,1)#3

#        StartTempMeas = QPushButton('StartTempMeas')
#        StartTempMeas.clicked.connect(lambda Tlist = np.arange(TStart.value(),TStop.value(),dT.value()): self.startTempMeas(Tlist))


    def startTempMeas(self,Tlist):
        for aname,achannelrow,rownumber in zip(self.Srbrainpanel.channelsDO,self.Srbrainpanel.timingboxes,range(len(self.Srbrainpanel.channelsDO))):
            if aname == 'CamTrigger':
                CamTriggerChannel = achannelrow
            elif aname=='ImagingAOM':
                AOMTriggerChannel = achannelrow
        CamWidth = CamTriggerChannel[1].value()-CamTriggerChannel[0].value() #find width of camtrigger pulses
        AOMWidth = AOMTriggerChannel[1].value() - AOMTriggerChannel[0].value()
        secondPulsedelay = CamTriggerChannel[2].value()-CamTriggerChannel[0].value()

        for aT in Tlist:
            CamTriggerChannel[0].setValue(aT)
            CamTriggerChannel[1].setValue(aT + CamWidth)
            CamTriggerChannel[2].setValue(secondPulsedelay + aT)
            CamTriggerChannel[3].setValue(secondPulsedelay + aT + CamWidth)

            AOMTriggerChannel[0].setValue(aT)
            AOMTriggerChannel[1].setValue(aT + AOMWidth)
            AOMTriggerChannel[2].setValue(secondPulsedelay + aT)
            AOMTriggerChannel[3].setValue(secondPulsedelay + aT + AOMWidth)

            self.Srbrainpanel.arm_patter()
            self.Srbrainpanel.Srbrain.stopSequence()
            self.waitbutton.toggle()
            time.sleep(1)
            self.Srbrainpanel.Srbrain.startSequence()
            time.sleep(1)
            self.collect_images()

        async def collect_images(self):
            self.tempcollecting = True
            while len(self.resultarray <= 10):
                asyncio.sleep(1)

            #now we have 10 images    
            y = np.array(list(range(0,np.size(self.resultarray[0],1))))
            x = np.array(list(range(0,np.size(self.resultarray[0],0))))
            X,Y = np.meshgrid(x,y)
            xdata = np.vstack((X.ravel(), Y.ravel()))
            poptarts = []

            for i in range(len(self.resultarray)):
                data = self.resultarray[i]
                try:
                    popt, pcov = curve_fit(_gaussian, xdata, data,p0, bounds = limit)
                except RuntimeError as e:
                    print(e)
                    popt = [0, 0, 0, 0, 0, 0]
                poptarts.append(popt)
                
                popt_array = np.array(poptarts)
                p0 = np.median(popt_array,axis=0) #we update the initial guess at each iteration

            sorted_results = self.sortinghat(poptarts,4)

            self.fitresults = poptarts



    def restore_GUI(self):
        pass
        '''
from qweather import QWeatherClient
import datetime
import time

QWeatherStationIP ="tcp://10.90.61.231:5559"
client = QWeatherClient(QWeatherStationIP,name='PztMeas',loop=None)

mm = client.AgiMM1
db = client.Database

while True:
	U = float(mm.measure_voltage())
	tstamp = datetime.datetime.now()
	timeNow = tstamp.timestamp()*1e9
	time.sleep(60)

	db.write('Repumper',tags={'Experiment':'Sr1'},fields={'Cavity Piezo Voltage':U},time=timeNow)
	print(("{:s}: {:.2f} Volt\n".format(str(tstamp),U)))
from qweather import QWeatherClient
import datetime
import time
import os
import numpy as np
cnx = QWeatherClient("tcp://10.90.61.231:5559")

serv1 = cnx.HP8648C

serv1.setFrequency(500)
serv1.getFrequency()
print('serv1.getFrequency')

print('Done')
class OscGui(QWidget):
    def __init__(self, loop=None):
        super().__init__()
        QWeatherStationIP = "tcp://10.90.61.231:5559"
        name = 'OscilloscopeGuiSR'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,
                                     name=name,
                                     loop=self.loop)
        self.setWindowTitle('Oscilloscopes')
        self.setFont(QtGui.QFont('Helvetica', 12))
        self.initialize_osc()
        self.initialize_GUI()
        self.restore_GUI()
        logging.getLogger().addHandler(self.logbox)
        logging.getLogger('asyncio').addHandler(self.logbox)
        logging.getLogger().setLevel(logging.DEBUG)
        logging.getLogger('asyncio').setLevel(logging.DEBUG)
        self.logbox.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s',
                              "%H:%M:%S"))
        self.PROCESS = psutil.Process(os.getpid())

        self.loop.create_task(self.client.run())

    def print_memory_usage(self):

        total, available, percent, used, free = psutil.virtual_memory()
        total, available, used, free = total / 10**6, available / 10**6, used / 10**6, free / 10**6
        proc = self.PROCESS.memory_info()[1] / 10**6
        print(
            'process = %s total = %s available = %s used = %s free = %s percent = %s'
            % (proc, total, available, used, free, percent))

    def initialize_osc(self):
        self.osclist = {}
        for aserv in self.client:
            if aserv.name[-3:] == 'OSC':
                self.osclist[aserv.name[:-3]] = aserv

    def initialize_GUI(self):
        oscselector = QComboBox()
        [oscselector.addItem(oscname) for oscname in self.osclist.keys()]

        filepath = QLineEdit()
        browsepath = QPushButton('...')

        browsepath.pressed.connect(
            lambda: filepath.setText(QFileDialog.getExistingDirectory() + '/'))

        scannumber = QSpinBox()
        scannumber.setRange(1, 100)

        channels = self.make_channel_panel()

        self.savebutton = QPushButton('SAVE')
        self.progressbar = QProgressBar()
        self.progressbar.setTextVisible(True)
        self.filetype = QComboBox()
        self.filetype.addItem('txt')
        self.filetype.addItem('h5')

        self.logbox = QTextEditLogger(self)
        self.logbox.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

        self.savebutton.pressed.connect(lambda: self.loop.create_task(
            (self.save_traces(filepath.text(), scannumber.value(),
                              oscselector.currentText()))))

        layout = QGridLayout()
        layout.addWidget(oscselector)
        layout.addWidget(filepath, 1, 0, 1, 6)
        layout.addWidget(browsepath, 1, 6, 1, 1)
        layout.addWidget(channels, 2, 0, 4, 2)
        layout.addWidget(scannumber, 2, 4)

        layout.addWidget(self.savebutton, 2, 5, 2, 2)
        layout.addWidget(self.filetype, 2, 7, 1, 2)
        layout.addWidget(self.progressbar, 4, 4, 1, 6)
        layout.addWidget(self.logbox.widget, 6, 0, 1, 10)
        self.setLayout(layout)

        self.show()

    async def save_traces(self, path, nscans, oscname):
        self.savebutton.setFlat(True)
        self.savebutton.setText('Working...')
        logging.info('Data taking begun')
        self.progressbar.setRange(0, nscans)
        osc = self.osclist[oscname]
        channels = [
            i + 1 for i in range(len(self.channellist))
            if self.channellist[i].isChecked()
        ]
        refchannels = [
            i + 1 for i in range(len(self.refchannellist))
            if self.refchannellist[i].isChecked()
        ]

        if len(path) == 0:
            errmsg = QMessageBox()
            errmsg.setText('No file path has been specified')
            errmsg.exec()
        elif len(channels) == 0:
            errmsg = QMessageBox()
            errmsg.setText('No channels have been specified')
            errmsg.exec()
        else:
            for j in range(nscans):
                data = []
                try:
                    for achannel in range(len(channels) - 1):
                        self.print_memory_usage()
                        tmp = await osc.single_measurement(channels[achannel])
                        logging.info('got data from channel {:d}'.format(
                            channels[achannel]))
                        data.append(tmp)
                    tmp = await osc.single_measurement(channels[-1]
                                                       )  #,rerun=True)
                    data.append(tmp)
                    logging.info(
                        'got data from channel {:d}, rerunning oscilloscope'.
                        format(channels[-1]))
                    newdata = [data[0][0], [adat[1] for adat in data]]
                    data = newdata
                    if len(refchannels) > 0:
                        refdata = []
                        for arefchannel in range(len(refchannels)):
                            tmp = await osc.single_measurement(
                                refchannels[arefchannel], ref=True)
                            refdata.append(tmp)
                        newdata = [
                            refdata[0][0], [adat[1] for adat in refdata],
                            refdata[0][2]
                        ]
                        refdata = newdata
                    logging.info('Got data from oscilloscope')
                except Exception as e:
                    logging.exception(e)
                    self.savebutton.setText('SAVE')
                    donebox = QMessageBox()
                    donebox.setText('Failed at getting data')
                    donebox.exec()
                try:
                    t = data[0]
                    chandata = data[1]
                    if len(refchannels) > 0:
                        reftime = refdata[0]
                        refchandata = refdata[1]

                    if self.filetype.currentText() == 'h5':
                        h5f = h5py.File(path + '_{:03d}.h5'.format(j + 1), 'w')
                        h5f.create_dataset('time', data=t)
                        for achan in range(len(chandata)):
                            h5f.create_dataset('chan_{:d}'.format(achan),
                                               data=chandata[achan])
                            logging.info('wrote data')
                        if len(refchannels) > 0:
                            h5f.create_dataset('reftime', data=reftime)
                            for achan in range(len(refchandata)):
                                h5f.create_dataset(
                                    'refchan_{:d}'.format(achan),
                                    data=refchandata[achan])
                        h5f.close()
                    elif self.filetype.currentText() == 'txt':
                        if len(data) == 3:
                            head = data[2]
                        else:
                            head = None
                        with open(path + '_{:03d}.txt'.format(j + 1),
                                  'w') as f:
                            headerstr = ''
                            if head is not None:
                                headerstr += 'Samplerate {:.3e}, Npoints {:}\n'.format(
                                    head[1], head[0])
                            headerstr += 'time(ms)'
                            for achan in channels:
                                headerstr += '\t Chan{:d} (V)'.format(achan)
                            f.write(headerstr + '\n')
                            NChans = len(chandata)
                            for apoint in zip(t, *chandata):
                                writestring = ""
                                writestring += '{:e}'.format(apoint[0])
                                for i in range(NChans):
                                    writestring += '\t {:e}'.format(apoint[i +
                                                                           1])
                                writestring += '\n'
                                f.write(writestring)

                        f.close()
                        if len(refchannels) > 0:
                            with open(path + 'Ref__{:03d}.txt'.format(j + 1),
                                      'w') as f:
                                headerstr = ''
                                if head is not None:
                                    headerstr += 'Samplerate {:.3e}, Npoints {:}\n'.format(
                                        head[1], head[0])
                                headerstr += 'time(ms)'
                                for achan in refchannels:
                                    headerstr += '\t RefChan{:d} (V)'.format(
                                        achan)
                                f.write(headerstr + '\n')
                                NChans = len(refchandata)
                                for apoint in zip(reftime, *refchandata):
                                    writestring = ""
                                    writestring += '{:e}'.format(apoint[0])
                                    for i in range(NChans):
                                        writestring += '\t {:e}'.format(
                                            apoint[i + 1])
                                    writestring += '\n'
                                    f.write(writestring)

                            f.close()
                except Exception as e:
                    logging.exception(e)
                    donebox = QMessageBox()
                    donebox.setText('Failed at saving')
                    donebox.exec()
                    print(e)
                logging.info('Saved data')
                self.progressbar.setValue(j + 1)
                time.sleep(0.5)
        self.savebutton.setFlat(False)
        donebox = QMessageBox()
        donebox.setText('Measurements done')
        donebox.exec()
        self.progressbar.reset()
        self.savebutton.setText('SAVE')

    def make_channel_panel(self):
        panel = QFrame()
        self.channellist = [QCheckBox() for i in range(4)]
        self.refchannellist = [QCheckBox() for i in range(4)]
        channellabel = [QLabel('{:d}'.format(i + 1)) for i in range(4)]
        refchannellabel = [QLabel('R{:d}'.format(i + 1)) for i in range(4)]
        channellabel2 = QLabel('Channels')
        channellabel2.setAlignment(QtCore.Qt.AlignCenter)
        layout = QGridLayout()
        for i in range(len(self.channellist)):
            layout.addWidget(self.channellist[i], 1, i)
            layout.addWidget(channellabel[i], 2, i)
        for i in range(len(self.refchannellist)):
            layout.addWidget(self.refchannellist[i], 3, i)
            layout.addWidget(refchannellabel[i], 4, i)

        layout.addWidget(channellabel2, 0, 0, 1, 4)

        panel.setLayout(layout)
        panel.setFrameStyle(0x00001)
        return panel

    def restore_GUI(self):
        settings = QtCore.QSettings('OscilloscopeGui.ini',
                                    QtCore.QSettings.IniFormat)

        for aspinbox in self.findChildren(QDoubleSpinBox) + self.findChildren(
                QSpinBox):
            name = aspinbox.objectName()
            if settings.contains(name):
                value = settings.value(name, type=float)
                aspinbox.setValue(value)

    def closeEvent(self, e):
        settings = QtCore.QSettings('OscilloscopeGui.ini',
                                    QtCore.QSettings.IniFormat)

        for aspinbox in self.findChildren(QDoubleSpinBox) + self.findChildren(
                QSpinBox):
            name = aspinbox.objectName()
            value = aspinbox.value()
            settings.setValue(name, value)

        settings.sync()
        self.loop.stop()
class SrBrainGui(QWidget):
    def __init__(self, loop=None):
        super().__init__()
        QWeatherStationIP = "tcp://10.90.61.231:5559"
        name = 'Sr1Gui'
        if loop is None:
            self.loop = asyncio.get_event_loop()
        else:
            self.loop = loop
        self.client = QWeatherClient(QWeatherStationIP,
                                     name=name,
                                     loop=self.loop)
        self.Srbrain = self.client.StrontiumBrain
        self.setWindowTitle('Strontium Pulse GUI')
        self.setFont(QtGui.QFont('Helvetica', 12))
        self.initialize_GUI()
        self.loop.create_task(self.client.run())

    def initialize_GUI(self):
        SRbrainpanel = self.make_SRbrainpanel()
        buttonpanel = self.make_buttonspanel()

        layout = QVBoxLayout()
        layout.addWidget(buttonpanel)
        layout.addWidget(SRbrainpanel)

        self.setLayout(layout)

        self.show()

    def make_SRbrainpanel(self):
        panel = QSplitter()

        timingpanel = QFrame()

        if self.Srbrain is None:
            layout = QHBoxLayout()
            layout.addWidget(QLabel('StrontiumBrain not connected...'))
            panel.setLayout(layout)
        else:
            self.channelsDO, channelsAI, self.channelsAO = self.Srbrain.getChannelList(
            )
            self.channelsDO = sorted(self.channelsDO)
            self.channelsAO = sorted(self.channelsAO)
            timinglayout = QtGui.QGridLayout()
            timinglayout.addWidget(QLabel('On/Off'), 0, 0)
            timinglayout.addWidget(QLabel('Name'), 0, 1)
            self.timeresolution = QComboBox()
            self.timeresolution.addItem('ms')
            self.timeresolution.setItemData(0, 1e-3)
            self.timeresolution.addItem('us')
            self.timeresolution.setItemData(1, 1e-6)
            self.timeresolution.setEditable(False)
            timinglayout.addWidget(self.timeresolution, 0, 2)
            #            timinglayout.addWidget(QLabel('Switches...'),0,2)
            helpbutton = QPushButton('Help')
            helpbutton.pressed.connect(lambda: QMessageBox.information(
                self, 'Oh shit - how does it work?',
                "Timings are in us.\nEach timing indicates a switch from the previous state,\nwithout knowledge of what the previous state was.\nIf On/Off is checked, an uneven number of switches must happen. Else an even.",
                QMessageBox.Ok))
            add = QPushButton('+')
            subtract = QPushButton('-')
            save = QPushButton('Save')
            load = QPushButton('Load')
            timinglayout.addWidget(add, 0, 3)
            timinglayout.addWidget(subtract, 0, 4)
            timinglayout.addWidget(save, 1, 2)
            timinglayout.addWidget(load, 1, 3)
            timinglayout.addWidget(helpbutton, 1, 4)
            self.timingboxesDO = []
            self.timingboxesAO = []
            self.tAO0 = []
            self.UAO0 = []
            self.tAO1 = []
            self.UAO1 = []
            self.tUnit = 1e3  # Multiply by 1e3 to view 0.001 s as 1 ms, etc...
            self.aopanels = []
            self.channelOnDict = {}
            for name in self.channelsDO:
                startOn = QCheckBox()
                label = QLabel(name)
                currentrow = timinglayout.rowCount()
                timinglayout.addWidget(startOn, currentrow, 0)
                timinglayout.addWidget(label, currentrow, 1)
                self.channelOnDict[name] = False

                startOn.stateChanged.connect(
                    lambda state, aname=name: self.onoff_changed(state, aname))

                self.timingboxesDO.append([])
                for i in range(3):
                    spinBox = mySpinbox()
                    self.timingboxesDO[-1].append(spinBox)
                    timinglayout.addWidget(self.timingboxesDO[-1][i],
                                           currentrow, i + 2)
            for name in self.channelsAO:
                startOn = QCheckBox()
                label = QLabel(name)
                currentrow = timinglayout.rowCount()
                timinglayout.addWidget(startOn, currentrow, 0)
                timinglayout.addWidget(label, currentrow, 1)
                self.channelOnDict[name] = False

                startOn.stateChanged.connect(
                    lambda state, aname=name: self.onoff_changed(state, aname))

                # Add button to configure AO signal and open popup. Unlike the DO boxes this is just informative and the info is edited with AO popup.
                if "0" in name:  # AO0 channel
                    self.aoconfig = QPushButton('Configure')
                    timinglayout.addWidget(self.aoconfig, currentrow, 2)
                    self.aoconfig.pressed.connect(
                        lambda: SrBrainGui.make_aowindow(self))
                elif "1" in name:  # AO1 channel
                    self.aoconfig1 = QPushButton('Configure')
                    timinglayout.addWidget(self.aoconfig1, currentrow, 2)
                    self.aoconfig1.pressed.connect(
                        lambda: SrBrainGui.make_aowindow1(self))

                # Add box to show the AO signal cycle time
                self.timingboxesAO.append([])
                spinBox = mySpinbox()
                self.timingboxesAO[-1].append(spinBox)
                timinglayout.addWidget(self.timingboxesAO[-1][0], currentrow,
                                       4)

            self.timeresolution.currentIndexChanged.connect(
                self.change_timeresolution)
            add.pressed.connect(lambda: self.modify_timings(
                self.timingboxesDO, timinglayout))  # Add switch time for DO
            subtract.pressed.connect(lambda: self.modify_timings(
                self.timingboxesDO, timinglayout, False)
                                     )  # Remove switch time for DO
            save.pressed.connect(self.timings_save)
            load.pressed.connect(lambda: self.timings_load(timinglayout))
            timingpanel.setLayout(timinglayout)

            self.plotfig = pg.PlotWidget()
            self.plotfig.setYRange(0, len(self.channelsDO))
            panel.addWidget(timingpanel)
            panel.addWidget(self.plotfig)
        return panel

    def change_timeresolution(self, index):
        timeres = self.timeresolution.itemData(index)
        if timeres == 1e-6:
            modifier = 1e3
        elif timeres == 1e-3:
            modifier = 1e-3

        for arow in self.timingboxesDO:
            for abox in arow:
                abox.setValue(abox.value() * modifier)

        for arow in self.timingboxesAO:
            for abox in arow:
                abox.setValue(abox.value() * modifier)

    def timings_save(self):
        savefilename, _ = QtGui.QFileDialog.getSaveFileName(
            None, 'Save file',
            'Z:\Dataprogrammer\Qweather\Config files\Timings.dat',
            'Timing files (*.dat)')
        if savefilename is not '':
            with open(savefilename, 'w') as f:
                f.write('Time resolution = ' +
                        self.timeresolution.currentText() + '\n')
                for aname, arow in zip(self.channelsDO, self.timingboxesDO):
                    f.write(aname)
                    for abox in arow:
                        f.write('\t' + str(abox.value()))
                    f.write('\n')

    def timings_load(self, layout):
        loadfilename, _ = QtGui.QFileDialog.getOpenFileName(
            None, 'Load file', 'Z:\Dataprogrammer\Qweather\Config files',
            'Timing files (*.dat)')
        loadchannels = []
        loadrows = []
        if loadfilename is not '':
            with open(loadfilename, 'r') as f:
                for line in f:
                    keyargs = line.split('=')
                    if len(keyargs) > 1:
                        if keyargs[0].strip() == 'Time resolution':
                            self.timeresolution.setCurrentText(
                                keyargs[1].strip())
                    else:
                        loadrows.append([])
                        columns = line.split('\t')
                        loadchannels.append(str(columns[0]))
                        for acolumn in columns[1:]:
                            loadrows[-1].append(float(acolumn))
                if self.channelsDO == loadchannels:
                    columns = len(loadrows[0])
                    while columns > len(self.timingboxesDO[0]):
                        self.modify_timings(self.timingboxesDO, layout)

                    for arow in range(len(loadrows)):
                        for acolumn in range(len(loadrows[arow])):
                            self.timingboxesDO[arow][acolumn].setValue(
                                loadrows[arow][acolumn])

    def make_buttonspanel(self):
        panel = QFrame()

        armButton = QPushButton('Arm Pattern')
        startTimingButton = QPushButton('Start Pattern')
        stopTimingButton = QPushButton('Stop Pattern')

        if self.Srbrain is not None:
            armButton.clicked.connect(self.arm_pattern)
            startTimingButton.clicked.connect(
                lambda state: self.Srbrain.startSequence())
            stopTimingButton.clicked.connect(
                lambda state: self.Srbrain.stopSequence())
        else:
            for i in [armbutton, startTimingButton, stopTimingButton]:
                i.setEnabled(False)

        layout = QGridLayout()
        layout.addWidget(armButton, 0, 0)
        layout.addWidget(startTimingButton, 0, 1)
        layout.addWidget(stopTimingButton, 0, 2)

        panel.setLayout(layout)
        return panel

    def onoff_changed(self, state, name):
        self.channelOnDict[name] = state

        self.Srbrain.clearDigitalSequence()
        self.Srbrain.clearAnalogOutput()
        for aname in self.channelsDO:
            if aname == name:
                if state:
                    self.Srbrain.addDigitalOutput(aname, 0, 1e-3)
                else:
                    self.Srbrain.addDigitalOutput(aname, 0, 0.5e-3)
        #self.Srbrain.clearAnalogSequence()
        for aname in self.channelsAO:
            if aname == name:
                if state:
                    self.Srbrain.addAnalogOutput(aname, 0, 1e-3)
                else:
                    self.Srbrain.addAnalogOutput(aname, 0, 0.5e-3)
        self.Srbrain.armSequence(self.UAO0, self.UAO1, user_Max_Time=1e-3)
        self.Srbrain.startSequence(run_only_once=True)

    def modify_timings(self,
                       boxes,
                       layout,
                       add=True):  # Add DO switch time boxes
        currwidth = len(boxes)

        if add:
            for i, arow in enumerate(boxes):
                spinBox = mySpinbox()
                arow.append(spinBox)
                layout.addWidget(arow[-1], i + 2, len(arow) + 1)
        else:
            for arow in boxes:
                layout.removeWidget(arow[-1])
                arow[-1].hide()
                del arow[-1]
        allrows = [field for row in boxes for field in row]
        for firstbox, followingbox in zip(allrows, allrows[1:]):
            self.setTabOrder(firstbox, followingbox)

    def arm_pattern(self):  # Arm digital and/or analog output patterns
        self.Srbrain.clearDigitalSequence()
        self.Srbrain.clearAnalogOutput()
        xdatalist = []
        ydatalist = []
        maxtime = 0
        for aname, achannelrow, rownumber in zip(self.channelsDO,
                                                 self.timingboxesDO,
                                                 range(len(self.channelsDO))):
            timings = sorted(
                list(
                    set([
                        i.value() * self.timeresolution.currentData()
                        for i in achannelrow
                    ])))
            if timings[0] == 0:
                timings.pop(0)
            xdata = []
            ydata = []
            ylow = 0.25 + len(self.channelsDO) + len(
                self.channelsAO) - rownumber - 1.5
            yhigh = 0.75 + len(self.channelsDO) + len(
                self.channelsAO) - rownumber - 1.5
            if self.channelOnDict[aname]:
                timings.insert(0, 0)
            if len(timings) % 2 != 0:
                pass
            else:
                for tstart, tstop in zip(timings[::2], timings[1::2]):
                    if tstop > maxtime:
                        maxtime = tstop
                    self.Srbrain.addDigitalOutput(aname, tstart, tstop)
                    xdata += [tstart, tstart, tstop, tstop]
                    if len(ydata) == 0:
                        ydata += [ylow, yhigh, yhigh, ylow]
                    else:
                        if ydata[-1] == yhigh:
                            ydata += [yhigh, ylow, ylow, yhigh]
                        else:
                            ydata += [ylow, yhigh, yhigh, ylow]
                xdatalist.append(np.array(xdata) * 1000)
                ydatalist.append(np.array(ydata))

        for aname, achannelrow, rownumber in zip(self.channelsAO,
                                                 self.timingboxesAO,
                                                 range(len(self.channelsAO))):

            if len(self.tAO0) > 0 or len(
                    self.tAO1
            ) > 0:  # Don't run this if there if the AO time array is empty
                if len(self.tAO0) > 0:
                    tstop = max(self.tAO0)
                else:
                    tstop = max(self.tAO1)
                if len(self.tAO1) > 0:
                    tstop = max({tstop, max(self.tAO1)})
                self.timingboxesAO[rownumber][0].setValue(
                    tstop / self.timeresolution.currentData()
                )  # Update value displayed in GUI
                if tstop > maxtime:
                    maxtime = tstop

                self.Srbrain.addAnalogOutput(aname, 0.0, tstop,
                                             5.0)  # Single value voltage

                if rownumber == 0 and len(self.tAO0) > 0:
                    xdatalist.append(
                        np.float(1e3) * np.linspace(0, tstop, len(
                            self.UAO0)))  # UAO should be type np.float64
                    UAOrescaled = 0.5 * (self.UAO0 - min(self.UAO0)) / (
                        max(self.UAO0) - min(self.UAO0)) + len(
                            self.channelsAO) - rownumber - 1.25
                    ydatalist.append(np.float(1) * UAOrescaled)
                elif rownumber == 1 and len(self.tAO1) > 0:
                    xdatalist.append(
                        np.float(1e3) * np.linspace(0, tstop, len(
                            self.UAO1)))  # UAO should be type np.float64
                    UAOrescaled = 0.5 * (self.UAO1 - min(self.UAO1)) / (
                        max(self.UAO1) - min(self.UAO1)) + len(
                            self.channelsAO) - rownumber - 1.25
                    ydatalist.append(np.float(1) * UAOrescaled)

        maxtime += 1e-6  #added this to prevent some corner crashes when two signals have to turn off at the end of the time sequence.

        self.plot_timings(xdatalist, ydatalist)  # Plot DO and AO signals
        self.Srbrain.armSequence(self.UAO0, self.UAO1, user_Max_Time=maxtime)

    def plot_timings(self, xlist, ylist):
        self.plotfig.clear()
        for i in range(len(xlist)):
            xdata = xlist[i]
            ydata = ylist[i]
            if len(xdata) > 0:
                self.plotfig.addItem(pg.InfiniteLine(min(ydata), angle=0))
                self.plotfig.addItem(pg.PlotCurveItem(xdata, ydata, pen='w'))

    def importAOdata(self, AOdata):  # Import AO data from AO popup window
        [self.tAO0, self.UAO0] = AOdata  # Get the data
        self.timingboxesAO[0][0].setValue(
            max(self.tAO0) /
            self.timeresolution.currentData())  # Update value displayed in GUI

    def importAOdata1(self, AOdata):  # Import AO data from AO popup window
        [self.tAO1, self.UAO1] = AOdata  # Get the data
        self.timingboxesAO[1][0].setValue(
            max(self.tAO1) /
            self.timeresolution.currentData())  # Update value displayed in GUI

    def make_aowindow(self):  # Make AO configuration popup window
        self.aopopup = aowindow()  # Make AO popup
        self.aopopup.sendAOsignal.connect(
            self.importAOdata)  # Connect to AO popup

    def make_aowindow1(self):  # Make AO configuration popup window
        self.aopopup1 = aowindow()  # Make AO popup
        self.aopopup1.sendAOsignal.connect(
            self.importAOdata1)  # Connect to AO popup
Esempio n. 13
0
'''Client to '''

from qweather import QWeatherClient
import numpy as np
import matplotlib.pyplot as plt

client = QWeatherClient('tcp://172.24.22.3:5559')
print('Connection Established')
freqserver = client.FreqCounter
print("Frequency Counter Server Found")
Npoints = 10000  # Number of points
gatetime = 20e-9  # gatetime
loggingtime = 1  #logging time, in seconds
data = freqserver.get_frequency(10000, 20e-9)

data = data.split(',')
data = [float(i[1:]) for i in data]

plt.figure()
plt.hist(data)
Esempio n. 14
0
from qweather import QWeatherClient
import os
import numpy
import datetime

cnx = QWeatherClient('tcp://10.90.61.13:5559')

serv = cnx.FreqCounter

tempDir = 'C:/Windows/Temp/Pendulum/'
saveDir = 'Z:/MicrowaveReference/data/190330'
gateTime = 0.1e-3  # Gate time in seconds
measTime = 10  # Total measuring time in seconds
nPoints = measTime / gateTime
# bufferSize = 10000	# Number of points i coounter buffer. Measure time will be minimum bufferSize*gateTime

print('Fetching frequency')
a = serv.log_frequency(gateTime, tempDir, measTime, False)
# a = serv.log_frequency(bufferSize,gateTime,measTime,False,tempDir)
#a = serv.log_frequency(10,20e-3,5)
print('Measuremenmt done')

hexFiles = os.listdir(tempDir)

if not os.path.exists(saveDir):
    os.mkdir(saveDir)

timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f')
fileHandleCSV = open(saveDir + timestamp + '.csv', 'w')

print('Saving data')