Example #1
0
    def open_file(self):
        """Open data file"""
        try:
            for i in self.mainwidget.imagewidget.plot.items:
                if dwwidg.is_flag(i):
                    msgBox = QMessageBox()
                    msgBox.setText(
                        "There are not saved flags! Are you sure to discard them?"
                    )
                    msgBox.addButton(QMessageBox.Cancel)
                    msgBox.addButton(QMessageBox.Ok)
                    msgBox.setDefaultButton(QMessageBox.Cancel)
                    ret = msgBox.exec_()
                    if ret == QMessageBox.Cancel:
                        return -1
                    elif ret == QMessageBox.Ok:
                        break
        except:
            pass

        self.toolbar.clear()
        try:
            self.flag_toolbar.close()
        except:
            pass
        try:
            self._open_file()
        except:
            msgBox = QMessageBox()
            msgBox.setText("File structure not recognized!")
            msgBox.exec_()
            return -1
Example #2
0
 def initStage(self):
     # TODO put this in thread and show egg clock
     if self.stage is not None:
         ## Create and display the splash screen
         #splash_pix = QPixmap('icons/piController.png')
         #splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
         #splash.setMask(splash_pix.mask())
         #splash.show()
         # TODO: give choice to select stage
         pitools.startup(self.stage, stages='M-112.1DG-NEW', refmode='FNL')
         #splash.close()
         # TODO: show dialog for waiting
         self.velocityLabel.setText('Velocity: {:f}mm/s'.format(
             self.stage.qVEL()['1']))
         self.velocity.setValue(int(1000 * self.stage.qVEL()['1']))
         self.stageConnected.emit()
         self._xAxeChanged()
         self.currentPos.setText('{:.7f}'.format(self.stage.qPOS()['1']))
         self.__startCurrPosThr()
         self.stageRange = (self.stage.qTMN()['1'], self.stage.qTMX()['1'])
         self.scanStep.validator().setBottom(0)
         self.initStageBtn.setEnabled(False)
     else:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText('No stage connected')
         msg.exec_()
Example #3
0
 def open(self):
     try:
         self._open()
     except:
         msgBox = QMessageBox()
         msgBox.setText("Wrong type of directory!")
         msgBox.exec_()
         return -1
Example #4
0
    def saveDataHDF5(self):
        import datetime
        import h5py

        now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S_FTIR')
        with h5py.File('data/{:s}.h5'.format(now)) as f:
            f.attrs['comments'] = self.fileUi.comment.text()
            f.attrs['stage'] = ''
            f.attrs['stage_settings'] = ''
            f.attrs['detector'] = ''
            f.attrs['detector_settings'] = ''

            # save time domain
            foo = self.tdWidget.calcFun.functions
            texts = [
                self.tdWidget.calcFun.itemText(i) for i in range(len(foo))
            ]
            dt = []
            for i in texts:
                dt.append(('x_{:s}'.format(i), np.float))
                dt.append(('y_{:s}'.format(i), np.float))
            dt = np.dtype(dt)
            dataTd = np.zeros(self.tdSignal.getData(foo[0][0])[0].shape[0],
                              dtype=dt)
            for i, fun in enumerate(foo):
                x, y = self.tdSignal.getData(
                    fun[0])  # [0]: fun, [1]: inverse fun
                dataTd['x_{:s}'.format(texts[i])] = x
                dataTd['y_{:s}'.format(texts[i])] = y
            dset = f.create_dataset('timeDomain', data=dataTd)
            self.tdSignal.plot.save_widget('data/{:s}_TD.png'.format(now))

            # save frequency domain
            foo = self.tdWidget.calcFun.functions
            texts = [
                self.tdWidget.calcFun.itemText(i) for i in range(len(foo))
            ]
            dt = []
            for i in texts:
                dt.append(('x_{:s}'.format(i), np.float))
                dt.append(('y_{:s}'.format(i), np.float))
            dt = np.dtype(dt)
            dataFd = np.zeros(self.fdSignal.getData(foo[0][0])[0].shape[0],
                              dtype=dt)
            for i, fun in enumerate(foo):
                x, y = self.fdSignal.getData(fun[0])
                dataFd['x_{:s}'.format(texts[i])] = x
                dataFd['y_{:s}'.format(texts[i])] = y
            #np.savetxt('data/{:s}_FD.txt'.format(now), dataFd, header=header)
            dset = f.create_dataset('frequencyDomain', data=dataFd)
            self.fdSignal.plot.save_widget('data/{:s}_FD.png'.format(now))

        # TODO: maybe put this in status bar
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText('Data saved')
        msg.exec_()
Example #5
0
 def connectStage(self):
     gcs = GCSDevice()
     try:
         gcs.InterfaceSetupDlg()
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Information)
         msg.setText(gcs.qIDN())
         msg.exec_()
         self.stage = gcs
         self.openStageBtn.setEnabled(False)
     except:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText('Could not connect stage')
         msg.exec_()
Example #6
0
 def properties_changed(self):
     row = self.imagelist.currentRow()
     image = self.images[row]
     try:
         image.x
     except:
         pass
     else:
         if ((self.properties.dataset.franges != 0
              and self.properties.dataset.franges < len(image.x)
              and self.properties.dataset.frangei <
              self.properties.dataset.franges)
                 or (self.properties.dataset.franges == 0
                     and self.properties.dataset.frangei < len(image.x))):
             pass
         else:
             msgBox = QMessageBox()
             msgBox.setText(
                 "Fit range void or out of bound! Range max 0:%s" %
                 (len(image.x) - 1))
             msgBox.exec_()
             return -1
     update_dataset(image, self.properties.dataset)
     #self.dssel.section = self.data_ref.list2choices(self.data_ref.sections[int(self.ds.dataset.feed)])
     csections.set(
         self.data_ref.list2choices(self.data_ref.sections[int(
             self.ds.dataset.feed)]))
     update_dataset(self.dssel, self.ds.dataset)
     self.update_info()
     if self.flagname:
         self.data_ref.flag = self.data_ref.get_flag_curve(
             self.flagname, self.dssel.section)
     #for i in self.images:
     #    i.otype = image.otype
     if image.rall == True:
         for i in self.images:
             i.rangei = image.rangei
             i.ranges = image.ranges
     if image.eall == True:
         for i in self.images:
             i.excluded = image.excluded
     for i in self.images:
         i.frangei = image.frangei
         i.franges = image.franges
     try:
         self.show_data(image.x, image.y, self.data_ref.flag)
     except:
         pass
Example #7
0
 def connectStage(self):
     gcs = GCSDevice(
         gcsdll="C:/Software/PI C863/PI_GCS2_DLL/PI_GCS2_DLL_x64.dll")
     try:
         gcs.InterfaceSetupDlg()
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Information)
         msg.setText(gcs.qIDN())
         msg.exec_()
         self.stage = gcs
         self.openStageBtn.setEnabled(False)
     except:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText('Could not connect stage')
         msg.exec_()
Example #8
0
    def _open_file(self):
        saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
        sys.stdout = None
        filename, _filter = getopenfilename(self, _("Open"), "")
        sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err

        if filename:
            extension = splitext(str(filename))[1]
            if extension not in ['.fits', '.hdf5', '.hdf', '.h5']:
                msgBox = QMessageBox()
                msgBox.setText("Wrong file type!")
                msgBox.exec_()
                return -1

            if extension == '.fits':
                file_type = "fits"
            elif extension == (".hdf5" or ".h5" or ".hdf"):
                msgBox = QMessageBox()
                msgBox.setText(
                    "Are data spectrometric or spectropolarimetric?")
                msgBox.addButton(QPushButton('Spect'), QMessageBox.NoRole)
                msgBox.addButton(QPushButton('Polar'), QMessageBox.YesRole)
                ret = msgBox.exec_()
                if ret == False:
                    widg_type = 0
                    file_type = 'hdf'
                elif ret == True:
                    widg_type = 1
                    file_type = 'hdf_pola'

            self.data = dwdata.DWData()
            self.data.open_data(filename, file_type)
            if file_type == 'fits':
                if self.data.data_type_dict[0][0] == 'simple':
                    widg_type = 0
                elif self.data.data_type_dict[0][0] == 'stokes':
                    widg_type = 1

            if widg_type == 0:
                self.setup_central_widget(dwwidg.MainWidget, self.toolbar)
            elif widg_type == 1:
                self.setup_central_widget(dwwidg.PolaViewerWidget,
                                          self.toolbar)
            self.set_flag_toolbar()

            self.mainwidget.open_setup(self.data)
            self.setWindowTitle(APP_NAME + " - " + filename)
Example #9
0
    def __openCam(self):
        self.camera = greatEyes()
        if not self.camera.connected:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('Sorry, could not connect to camera :(\n' + 
                    self.camera.status)
            msg.exec_()
            return
        self.openCamBtn.setText('Connected')
        self.message.emit('Camera connected')
        self.openCamBtn.setStyleSheet('QPushButton {color: green;}')

        self.readoutSpeedCombo.setEnabled(True)
        self.exposureTimeSpin.setEnabled(True)
        self.binningXCombo.setEnabled(False)
        self.binningYCombo.setEnabled(False)
        self.temperatureSpin.setEnabled(True)
        self.updateInterSpin.setEnabled(True)

        self.openCamBtn.setEnabled(False)
        self.startAquBtn.setEnabled(True) 
Example #10
0
    def saveData(self):
        import datetime
        now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')

        # save time domain
        foo = self.tdWidget.calcFun.functions
        texts = [self.tdWidget.calcFun.itemText(i) for i in range(len(foo))]
        tmp = ['td_x_{:s},td_y_{:s}'.format(i, i) for i in texts] 
        header = ','.join(tmp)
        dataTd = np.zeros((self.tdSignal.getData(foo[0][0])[0].shape[0],
                          2*len(foo)))
        for i, fun in enumerate(foo):
            x, y =  self.tdSignal.getData(fun[0])# [0]: fun, [1]: inverse fun
            dataTd[:,2*i] = x
            dataTd[:,2*i+1] = y
        np.savetxt('data/{:s}_TD.txt'.format(now), dataTd, header=header)
        self.tdSignal.plot.save_widget('data/{:s}_TD.png'.format(now))
        
        # save frequency domain
        foo = self.fdWidget.calcFun.functions
        texts = [self.fdWidget.calcFun.itemText(i) for i in range(len(foo))]
        tmp = ['fd_x_{:s},fd_y_{:s}'.format(i, i) for i in texts] 
        header += ','.join(tmp)
        dataFd = np.zeros((self.fdSignal.getData(foo[0][0])[0].shape[0],
                          2*len(foo)))
        for fun in foo:
            x, y = self.fdSignal.getData(fun[0])
            dataFd[:,2*i] = x
            dataFd[:,2*i+1] = y
        np.savetxt('data/{:s}_FD.txt'.format(now), dataFd, header=header)
        self.fdSignal.plot.save_widget('data/{:s}_FD.png'.format(now))

        # TODO: maybe put this in status bar
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText('Data saved')
        msg.exec_()
Example #11
0
    def fitfile(self):
        if self.fitc == None:
            msgBox = QMessageBox()
            msgBox.setText("Fit not yet executed!")
            msgBox.exec_()
            return -1

        msgBox = QMessageBox()
        msgBox.setText("Save correction file?")
        #msgBox.setInformativeText("A correction file will be saved in the root directory of the observation.")
        msgBox.addButton(QMessageBox.Cancel)
        msgBox.addButton(QMessageBox.Ok)
        msgBox.setDefaultButton(QMessageBox.Cancel)
        ret = msgBox.exec_()
        if ret != QMessageBox.Ok:
            return -1

        name = getsavefilename(self,
                               _("Save File"),
                               self.data_ref.dir_name + "/" + basename(
                                   normpath(self.data_ref.dir_name) + "_fit." +
                                   self.data_ref.files_type),
                               options=QFileDialog.DontConfirmOverwrite)
        if str(name[0]):
            if exists(str(name[0])):
                msgBox = QMessageBox()
                msgBox.setText("File exists!")
                msgBox.setInformativeText("Do you want to update it?")
                msgBox.addButton(QMessageBox.Cancel)
                msgBox.addButton(QMessageBox.Ok)
                msgBox.setDefaultButton(QMessageBox.Cancel)
                ret = msgBox.exec_()
                if ret != QMessageBox.Ok:
                    return -1

            self.data_ref.fitfile(str(name[0]), self.fitc)
Example #12
0
 def close_dw(self):
     """Close DW"""
     try:
         for i in self.mainwidget.imagewidget.plot.items:
             if dwwidg.is_flag(i):
                 msgBox = QMessageBox()
                 msgBox.setText(
                     "There are not saved flags! Are you sure to discard them?"
                 )
                 msgBox.addButton(QMessageBox.Cancel)
                 msgBox.addButton(QMessageBox.Ok)
                 msgBox.setDefaultButton(QMessageBox.Cancel)
                 ret = msgBox.exec_()
                 if ret == QMessageBox.Cancel:
                     return -1
                 elif ret == QMessageBox.Ok:
                     break
         self.close()
     except:
         self.close()
Example #13
0
    def close_file(self):
        """Close data file"""
        for i in self.mainwidget.imagewidget.plot.items:
            if dwwidg.is_flag(i):
                msgBox = QMessageBox()
                msgBox.setText(
                    "There are not saved flags! Are you sure to discard them?")
                msgBox.addButton(QMessageBox.Cancel)
                msgBox.addButton(QMessageBox.Ok)
                msgBox.setDefaultButton(QMessageBox.Cancel)
                ret = msgBox.exec_()
                if ret == QMessageBox.Cancel:
                    return -1
                elif ret == QMessageBox.Ok:
                    break

        self.mainwidget.close()
        self.toolbar.clear()
        self.flag_toolbar.close()
        self.data.close()
        del self.data
        del self.mainwidget
        self.setWindowTitle(APP_NAME)
Example #14
0
    def apply_fit(self):
        msgBox = QMessageBox()
        msgBox.setText("Apply corrections?")
        msgBox.setInformativeText(
            "Select to which files will be applied the correction.")
        CancelButton = msgBox.addButton("Cancel", msgBox.RejectRole)
        SelectButton = msgBox.addButton("Select", msgBox.NoRole)
        AllButton = msgBox.addButton("All", msgBox.YesRole)
        #msgBox.setDefaultButton(QMessageBox.Cancel)
        msgBox.exec_()
        if msgBox.clickedButton() == CancelButton:
            return -1
        elif msgBox.clickedButton() == AllButton:
            filelist = None
        elif msgBox.clickedButton() == SelectButton:
            flret = getopenfilenames(self, _("Select file list"),
                                     self.data_ref.dir_name)[0]
            filelist = []
            for f in flret:
                filelist.append((basename(str(f)), dirname(str(f))))
            msgBox = QMessageBox()
            msgBox.setText("Select the correction file")
            msgBox.addButton(QMessageBox.Ok)
            msgBox.exec_()

        filename = getopenfilename(
            self, _("Correction file"),
            self.data_ref.dir_name + "/" + basename(
                normpath(self.data_ref.dir_name) + "_fit." +
                self.data_ref.files_type))
        try:
            self.data_ref.applycorr(str(filename[0]), filelist)
        except:
            msgBox = QMessageBox()
            msgBox.setText("Not a correction file!")
            msgBox.exec_()
            return -1
Example #15
0
    def openDev(self):
        # search for devices
        libtiepie.device_list.update()
        # try to open an oscilloscope with block measurement support
        for item in libtiepie.device_list:
            if item.can_open(libtiepie.DEVICETYPE_OSCILLOSCOPE):
                self.scp = item.open_oscilloscope()
                if self.scp.measure_modes & libtiepie.MM_BLOCK:
                    break
                else:
                    self.scp = None
        # init UI
        #print(self.scp.name, 'found')
        if self.scp is not None:
            # Set measure mode:
            self.scp.measure_mode = libtiepie.MM_BLOCK

            # Set sample frequency:
            self.scp.sample_frequency = 1e6  # 1 MHz

            # Set record length:
            self.scp.record_length = 10000  # 10000 samples

            # Set pre sample ratio:
            self.scp.pre_sample_ratio = 0  # 0 %

            # Set trigger timeout:
            self.scp.trigger_time_out = 100e-3  # 100 ms

            # Enable channel 1 for measurement
            # http://api.tiepie.com/libtiepie/0.5/group__scp__ch__enabled.html
            self.scp.channels[
                0].enabled = True  # by default all channels are enabled
            self.scp.range = 0.2
            self.scp.coupling = libtiepie.CK_DCV  # DC Volt

            # Disable all channel trigger sources
            for ch in self.scp.channels:
                ch.trigger.enabled = False
            # Setup channel trigger on 1
            ch = self.scp.channels[0]
            ch.trigger.enabled = True
            ch.trigger.kind = libtiepie.TK_RISINGEDGE
            ch.trigger.levels[0] = 0.5  # 50%
            ch.trigger.hystereses[0] = 0.05  # 5%

            # update UI
            # channel
            self.measCh.addItems(
                ['Ch{:d}'.format(i) for i in range(self.scp.channels.count)])
            self.chSens.addItems(
                ['{:.1f} V'.format(i) for i in self.scp.channels[0].ranges])
            self.frequency.setValidator(
                QIntValidator(1, 1e-3 * self.scp.sample_frequency_max))
            self.frequency.setText('{:d}'.format(
                int(self.scp.sample_frequency * 1e-3)))
            self.recordLen.setValidator(
                QIntValidator(1, self.scp.record_length_max))
            self.recordLen.setText('{:d}'.format(self.scp.record_length))
            # trigger
            self.triggCh.addItems(
                ['Ch{:d}'.format(i) for i in range(self.scp.channels.count)])
            # TODO: doen't work in module anymore!!
            #self.triggLevel.setText(str(ch.trigger.levels[0]))
            #self.hystereses.setText(str(ch.trigger.hystereses[0]))
            self.triggKind.addItems([
                '{:s}'.format(i) for i in libtiepie.trigger_kind_str(
                    ch.trigger.kinds).split(', ')
            ])

            self.openDevBtn.setEnabled(False)

            # tell the world that the scope is connected
            self.xAxeChanged.emit(
                0, 1 / int(self.frequency.text()) * 1e-3 *
                int(self.recordLen.text()))
            self.yAxeChanged.emit(-1 * self.scp.range, self.scp.range)
            self.triggLevelChanged.emit(ch.trigger.levels[0] * 2 *
                                        self.scp.range - self.scp.range)
            self.scpConnected.emit()

        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('No supported device found')
            msg.exec_()