Пример #1
0
    def plot(self):
        if self.plotDialog is None:
            from PyMca5.PyMcaGui.plotting.PlotWindow import PlotWindow
            dialog = qt.QDialog(self)
            dialog.mainLayout = qt.QVBoxLayout(dialog)
            dialog.mainLayout.setContentsMargins(0, 0, 0, 0)
            dialog.mainLayout.setSpacing(0)
            dialog.plotWidget = PlotWindow(dialog,
                                           newplot=False,
                                           fit=False,
                                           plugins=False,
                                           control=True,
                                           position=True)
            dialog.plotWidget.setDefaultPlotLines(True)
            dialog.plotWidget.setDefaultPlotPoints(True)
            dialog.plotWidget.setDataMargins(0.05, 0.05, 0.05, 0.05)
            dialog.mainLayout.addWidget(dialog.plotWidget)
            self.plotDialog = dialog

        legend = self._transmissionTable["name"]
        if legend == "":
            legend = None
        x = self._transmissionTable["energy"]
        y = self._transmissionTable["transmission"]
        comment = self._transmissionTable["comment"]
        self.plotDialog.plotWidget.addCurve(x,
                                 y,
                                 legend=legend,
                                 xlabel="Energy (keV)",
                                 ylabel="Transmission",
                                 replot=True,
                                 replace=True)
        self.plotDialog.plotWidget.setGraphTitle(comment)
Пример #2
0
 def _startThread(self, sthread, message):
     sthread.start()
     msg = qt.QDialog(self, qt.Qt.FramelessWindowHint)
     msg.setModal(1)
     msg.setWindowTitle("Please Wait")
     layout = qt.QHBoxLayout(msg)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     l1 = qt.QLabel(msg)
     l1.setFixedWidth(l1.fontMetrics().width('##'))
     l2 = qt.QLabel(msg)
     l2.setText("%s" % message)
     l3 = qt.QLabel(msg)
     l3.setFixedWidth(l3.fontMetrics().width('##'))
     layout.addWidget(l1)
     layout.addWidget(l2)
     layout.addWidget(l3)
     msg.show()
     qApp = qt.QApplication.instance()
     qApp.processEvents()
     i = 0
     ticks = ['-', '\\', "|", "/", "-", "\\", '|', '/']
     while (sthread.isRunning()):
         i = (i + 1) % 8
         l1.setText(ticks[i])
         l3.setText(" " + ticks[i])
         qApp = qt.QApplication.instance()
         qApp.processEvents()
         time.sleep(2)
     msg.close()
     result = sthread._result
     del sthread
     self.raise_()
     return result
Пример #3
0
def getDatasetDialog(filename=None, value=False, message=None):
    """
    Simple dialog to select a dataset via a double click on the tree

    :param filename: Name of the HDF5 file
    :param value: If True returns dataset value instead of just the dataset
    """
    if filename is None:
        from PyMca5.PyMca import PyMcaFileDialogs
        fileTypeList = ['HDF5 Files (*.h5 *.nxs *.hdf)', 'HDF5 Files (*)']
        message = "Open HDF5 file"
        filenamelist, ffilter = PyMcaFileDialogs.getFileList(
            parent=None,
            filetypelist=fileTypeList,
            message=message,
            getfilter=True,
            single=True,
            currentfilter=None)
        if len(filenamelist) < 1:
            return None
        filename = filenamelist[0]
    if message is None:
        message = 'Select your item by a double click'
    hdf5Dialog = qt.QDialog()
    hdf5Dialog.setWindowTitle(message)
    hdf5Dialog.mainLayout = qt.QVBoxLayout(hdf5Dialog)
    hdf5Dialog.mainLayout.setContentsMargins(0, 0, 0, 0)
    hdf5Dialog.mainLayout.setSpacing(0)
    fileModel = FileModel()
    fileView = HDF5Widget(fileModel)
    hdf5File = fileModel.openFile(filename, "r")

    def _hdf5WidgetSlot(ddict):
        if ddict['event'] == "itemDoubleClicked":
            if ddict['type'].lower() in ['dataset']:
                hdf5Dialog._hdf5Datatset = ddict['name']
                hdf5Dialog.accept()

    fileView.sigHDF5WidgetSignal.connect(_hdf5WidgetSlot)
    hdf5Dialog.mainLayout.addWidget(fileView)
    hdf5Dialog.resize(400, 200)
    ret = hdf5Dialog.exec_()
    if not ret:
        return None
    dataset = hdf5Dialog._hdf5Datatset
    hdf5Dialog = None
    if value:
        data = hdf5File[dataset].value
        # is it dangerous to close the file?
        hdf5File.close()
    else:
        data = hdf5File[dataset]
    return data
Пример #4
0
 def _massAttenuationSlot(self, ddict):
     try:
         compoundList = ddict['CompoundList']
         fractionList = ddict['CompoundFraction']
         energy = numpy.arange(1, 100, 0.1)
         data = Elements.getMaterialMassAttenuationCoefficients(
             compoundList, fractionList, energy)
         addButton = False
         if self.graph is None:
             # probably dead code (ScanWindow.ScanWindow not imported)
             self.graphDialog = qt.QDialog(self)
             self.graphDialog.mainLayout = qt.QVBoxLayout(self.graphDialog)
             self.graphDialog.mainLayout.setContentsMargins(0, 0, 0, 0)
             self.graphDialog.mainLayout.setSpacing(0)
             #self.graph = ScanWindow.ScanWindow(self.graphDialog)
             self.graph = ScanWindow(self.graphDialog)
             self.graphDialog.mainLayout.addWidget(self.graph)
             self.graph._togglePointsSignal()
             self.graph.graph.crossPicker.setEnabled(False)
             addButton = True
         if addButton:
             self._addGraphDialogButton()
         self.graph.setGraphTitle(ddict['Comment'])
         legend = 'Coherent'
         self.graph.addCurve(energy,
                             numpy.array(data[legend.lower()]),
                             legend=legend,
                             xlabel='Energy (keV)',
                             ylabel='Mass Att. (cm2/g)',
                             replace=True,
                             replot=False)
         for legend in ['Compton', 'Photo', 'Total']:
             self.graph.addCurve(energy,
                                 numpy.array(data[legend.lower()]),
                                 legend=legend,
                                 xlabel='Energy (keV)',
                                 ylabel='Mass Att. (cm2/g)',
                                 replace=False,
                                 replot=False)
         self.graph.setActiveCurve(legend + ' ' + 'Mass Att. (cm2/g)')
         self.graph.setGraphTitle(ddict['Comment'])
         if self.graphDialog is not None:
             self.graphDialog.exec()
     except:
         msg = qt.QMessageBox(self)
         msg.setIcon(qt.QMessageBox.Critical)
         msg.setInformativeText(str(sys.exc_info()[1]))
         msg.setDetailedText(traceback.format_exc())
         msg.exec()
Пример #5
0
 def _transmissionSlot(self, ddict):
     try:
         compoundList = ddict['CompoundList']
         fractionList = ddict['CompoundFraction']
         density = ddict['Density']
         thickness = ddict.get('Thickness', 0.1)
         energy = numpy.arange(1, 100, 0.1)
         data = Elements.getMaterialTransmission(compoundList,
                                                 fractionList,
                                                 energy,
                                                 density=density,
                                                 thickness=thickness,
                                                 listoutput=False)
         addButton = False
         if self.graph is None:
             # probably dead code (ScanWindow not imported)
             self.graphDialog = qt.QDialog(self)
             self.graphDialog.mainLayout = qt.QVBoxLayout(self.graphDialog)
             self.graphDialog.mainLayout.setContentsMargins(0, 0, 0, 0)
             self.graphDialog.mainLayout.setSpacing(0)
             #self.graph = ScanWindow.ScanWindow(self.graphDialog)
             self.graph = ScanWindow(self.graphDialog)
             self.graphDialog.mainLayout.addWidget(self.graph)
             self.graph._togglePointsSignal()
             self.graph.graph.crossPicker.setEnabled(False)
             addButton = True
         if addButton:
             self._addGraphDialogButton()
         if self.__toolMode:
             legend = ddict['Comment']
         else:
             legend = str(self.matCombo.currentText()) +\
                      " with density = %f g/cm3" % density +\
                      " and thickness = %f cm" % thickness
         self.graph.addCurve(energy,
                             data['transmission'],
                             legend=legend,
                             xlabel='Energy (keV)',
                             ylabel='Transmission',
                             replace=True)
         self.graph.setGraphTitle(ddict['Comment'])
         if self.graphDialog is not None:
             self.graphDialog.exec()
     except:
         msg = qt.QMessageBox(self)
         msg.setIcon(qt.QMessageBox.Critical)
         msg.setInformativeText(str(sys.exc_info()[1]))
         msg.setDetailedText(traceback.format_exc())
         msg.exec()
Пример #6
0
 def _loadIniFromHdf5(self, filename):
     self.__hdf5Dialog = qt.QDialog()
     self.__hdf5Dialog.setWindowTitle('Select the fit configuration dataset by a double click')
     self.__hdf5Dialog.mainLayout = qt.QVBoxLayout(self.__hdf5Dialog)
     self.__hdf5Dialog.mainLayout.setContentsMargins(0, 0, 0, 0)
     self.__hdf5Dialog.mainLayout.setSpacing(0)
     fileModel = HDF5Widget.FileModel()
     fileView = HDF5Widget.HDF5Widget(fileModel)
     with h5py.File(filename, "r") as hdfFile:
         fileModel.appendPhynxFile(hdfFile, weakreference=True)
         fileView.sigHDF5WidgetSignal.connect(self._hdf5WidgetSlot)
         self.__hdf5Dialog.mainLayout.addWidget(fileView)
         self.__hdf5Dialog.resize(400, 200)
         ret = self.__hdf5Dialog.exec_()
         if ret:
             initxt = hdfFile[self.__fitConfigDataset][()]
         else:
             initxt = None
     return initxt
    def configureFilter(self):
        if self._widget is None:
            # construct a widget
            msg = qt.QDialog()
            msg.setWindowTitle("Deglitch Configuration")
            msgLayout = qt.QGridLayout()
            buttonLayout = qt.QHBoxLayout()

            inpThreshold = qt.QDoubleSpinBox()
            inpThreshold.setRange(0.,10.)
            inpThreshold.setSingleStep(.1)
            inpThreshold.setValue(self.threshold)
            inpThreshold.setToolTip('Increase width for broad spikes')

            inpWidth = qt.QSpinBox()
            inpWidth.setRange(1,101)
            inpWidth.setSingleStep(2)
            inpWidth.setValue(self.width)
            inpWidth.setToolTip('Set low threshold for multiple spikes of different markedness')

            labelWidth = qt.QLabel('Width (must be odd)')
            labelThreshold = qt.QLabel('Threshold (multiple of deviation)')
            buttonOK = qt.QPushButton('Ok')
            buttonOK.clicked.connect(msg.accept)
            buttonCancel = qt.QPushButton('Cancel')
            buttonCancel.clicked.connect(msg.reject)

            allActiveBG = qt.QButtonGroup()
            buttonAll = qt.QCheckBox('Apply to All')
            buttonActive = qt.QCheckBox('Apply to Active')
            allActiveBG.addButton(buttonAll, 0)
            allActiveBG.addButton(buttonActive, 1)
            buttonActive.setChecked(True)

            buttonLayout.addWidget(qt.HorizontalSpacer())
            buttonLayout.addWidget(buttonOK)
            buttonLayout.addWidget(buttonCancel)

            msgLayout.addWidget(labelWidth,0,0)
            msgLayout.addWidget(inpWidth,0,1)
            msgLayout.addWidget(labelThreshold,1,0)
            msgLayout.addWidget(inpThreshold,1,1)
            msgLayout.addWidget(buttonActive,2,0)
            msgLayout.addWidget(buttonAll,2,1)
            msgLayout.addLayout(buttonLayout,3,0,1,2)
            msg.setLayout(msgLayout)
            msg.inputWidth = inpWidth
            msg.inputThreshold = inpThreshold
            msg.applyToAll =  buttonAll
            self._widget = msg
            self._widget.buttonActive = buttonActive
            self._widget.buttonAll = buttonAll
        if self._widget.exec():
            self.threshold = float(self._widget.inputThreshold.value())
            self.width = int(self._widget.inputWidth.value())
            if not (self.width%2):
                self.width += 1
            if self._widget.buttonAll.isChecked():
                _logger.debug('AllChecked')
                self.removeSpikesAll()
            elif self._widget.buttonActive.isChecked():
                _logger.debug('ActiveChecked')
                self.removeSpikesActive()
Пример #8
0
    def _shiftFromFile(self):
        stack = self.getStackDataObject()
        if stack is None:
            return
        data = stack.data
        mcaIndex = stack.info.get('McaIndex')
        if not (mcaIndex in [0, -1, 2]):
            raise IndexError("1D index must be 0, 2, or -1")
        filefilter = ['HDF5 Files (*.h5 *.nxs *.hdf *.hdf5)', 'CSV 2-column (*.csv)', 'ASCII 2-column (*)']
        filename, ffilter = PyMcaFileDialogs.\
                    getFileList(parent=None,
                        filetypelist=filefilter,
                        message='Load',
                        mode='OPEN',
                        single=True,
                        getfilter=True,
                        currentfilter=filefilter[0])
        if len(filename):
            _logger.debug("file name = %s file filter = %s", filename, ffilter)
        else:
            _logger.debug("nothing selected")
            return
        filename = filename[0]
        if ffilter.startswith('HDF5'):
            # browse
            self.__hdf5Dialog = qt.QDialog()
            self.__hdf5Dialog.setWindowTitle('Select your data set by a double click')
            self.__hdf5Dialog.mainLayout = qt.QVBoxLayout(self.__hdf5Dialog)
            self.__hdf5Dialog.mainLayout.setContentsMargins(0, 0, 0, 0)
            self.__hdf5Dialog.mainLayout.setSpacing(0)
            fileModel = HDF5Widget.FileModel()
            fileView = HDF5Widget.HDF5Widget(fileModel)
            with h5py.File(filename, "r") as hdfFile:
                fileModel.appendPhynxFile(hdfFile, weakreference=True)
                self.__shiftsDataset = None
                fileView.sigHDF5WidgetSignal.connect(self._hdf5WidgetSlot)
                self.__hdf5Dialog.mainLayout.addWidget(fileView)
                self.__hdf5Dialog.resize(400, 200)
                ret = self.__hdf5Dialog.exec_()
                if not ret:
                    return
                shifts = hdfFile[self.__shitfsDataset].value
        else:
            sf = specfilewrapper.Specfile(filename)
            nScans = len(sf)
            targetScan = None
            for scan in sf:
                if scan.lines() ==  data.shape[stack.info['McaIndex']]:
                    targetScan = scan
                    break
            if targetScan is None:
                scan = None
                sf = None
                raise IOError("Number of read lines does not match stack shape")
            shifts = targetScan.data()
            targetScan = None
            scan = None
            sf = None
            if shifts.shape[0] == 3 and\
               shifts.shape[1] == data.shape[stack.info['McaIndex']]:
                # one column was added (point number)
                shifts = shifts[1:].T

        filename = None
        if not isinstance(data, numpy.ndarray):
            filefilter = ['HDF5 Files (*.h5)']
            filename = PyMcaFileDialogs.\
                        getFileList(parent=None,
                        filetypelist=filefilter,
                        message='Select output file',
                        mode='SAVE',
                        single=True,
                        getfilter=False,
                        currentfilter=filefilter[0])
            if len(filename):
                filename = filename[0]
                _logger.debug("file name = %s", filename)
            else:
                raise IOError("No output file selected")
        if filename is not None:
            self.__hdf5 = self.initializeHDF5File(filename)
        crop = False
        if _logger.getEffectiveLevel() == logging.DEBUG:
            result = self.shiftStack(stack,
                                     shifts,
                                     crop=crop,
                                     filename=filename)
        else:
            result = self.__shiftStack(stack,
                                       shifts,
                                       crop=crop,
                                       filename=filename)
            if result is not None:
                # exception occurred
                raise Exception(result[1], result[2], result[3])

        if filename is not None:
            hdf = self.__hdf5
            alignmentGroup = hdf['/entry_000/Alignment']
            outputShifts = self.getHDF5BufferIntoGroup(alignmentGroup,
                                                 shape=(stack.data.shape[mcaIndex], 2),
                                                 name="shifts",
                                                 dtype=numpy.float32)
            outputShifts[:,:] = shifts
            attributes={'interpretation':'image'}
            # fill the axes information
            dataGroup = hdf['/entry_000/Data']
            if mcaIndex == 0:
                reference_shape = data[0].shape
            else:
                reference_shape = data.shape[0], data.shape[1]
            try:
                activeCurve = self.getActiveCurve()
                if activeCurve is None:
                    activeCurve = self.getAllCurves()[0]
                x, y, legend, info = activeCurve
                dataGroup[info['xlabel']] = numpy.array(x, dtype=numpy.float32)
                dataGroup[info['xlabel']].attrs['axis'] = numpy.int32(1)
                axesAttribute = '%s:dim_1:dim_2' % info['xlabel']
            except:
                if _logger.getEffectiveLevel() == logging.DEBUG:
                    raise
                dataGroup['dim_0'] = numpy.arange(stack.data.shape[mcaIndex]).astype(numpy.float32)
                dataGroup['dim_0'].attrs['axis'] = numpy.int32(1)
                axesAttribute = 'dim_0:dim_1:dim_2'
            dataGroup['dim_1'] = numpy.arange(reference_shape[0]).astype(numpy.float32)
            dataGroup['dim_1'].attrs['axis'] = numpy.int32(2)
            dataGroup['dim_2'] = numpy.arange(reference_shape[1]).astype(numpy.float32)
            dataGroup['dim_2'].attrs['axis'] = numpy.int32(3)
            dim2 = numpy.arange(reference_shape[1]).astype(numpy.float32)
            dataGroup['data'].attrs['axes'] = axesAttribute
            self.finishHDF5File(hdf)
        else:
            self.setStack(stack)
Пример #9
0
def waitingMessageDialog(thread,
                         message=None,
                         parent=None,
                         modal=True,
                         update_callback=None,
                         frameless=False):
    """
    thread  - The thread to be polled
    message - The initial message to be diplayed
    parent  - The parent QWidget. It is used just to provide a convenient localtion
    modal   - Default is True. The dialog will prevent user from using other widgets
    update_callback - The function to be called to provide progress feedback. It is expected
             to return a dictionary. The recognized key words are:
             message: The updated message to be displayed.
             title: The title of the window title.
             progress: A number between 0 and 100 indicating the progress of the task.
             status: Status of the calculation thread.
    """
    if message is None:
        message = "Please wait. Calculation going on."
    windowTitle = "Please Wait"
    if frameless:
        msg = qt.QDialog(None, qt.Qt.FramelessWindowHint)
    else:
        msg = qt.QDialog(None)

    #if modal:
    #    msg.setWindowFlags(qt.Qt.Window | qt.Qt.CustomizeWindowHint | qt.Qt.WindowTitleHint)
    msg.setModal(modal)
    msg.setWindowTitle(windowTitle)
    layout = qt.QHBoxLayout(msg)
    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)
    l1 = qt.QLabel(msg)
    l1.setFixedWidth(l1.fontMetrics().maxWidth() * len('##'))
    l2 = qt.QLabel(msg)
    l2.setText("%s" % message)
    l3 = qt.QLabel(msg)
    l3.setFixedWidth(l3.fontMetrics().maxWidth() * len('##'))
    layout.addWidget(l1)
    layout.addWidget(l2)
    layout.addWidget(l3)
    msg.show()
    if parent is not None:
        # place the dialog at appropriate point
        parentGeometry = parent.geometry()
        x = parentGeometry.x() + 0.5 * parentGeometry.width()
        y = parentGeometry.y() + 0.5 * parentGeometry.height()
        msg.move(int(x - 0.5 * msg.width()), int(y))
    t0 = time.time()
    i = 0
    ticks = ['-', '\\', "|", "/", "-", "\\", '|', '/']
    qApp = qt.QApplication.instance()
    if update_callback is None:
        while (thread.isRunning()):
            i = (i + 1) % 8
            l1.setText(ticks[i])
            l3.setText(" " + ticks[i])
            qApp.processEvents()
            if QTHREAD:
                qt.QThread.msleep(1000)
            else:
                time.sleep(2)
    else:
        while (thread.isRunning()):
            updateInfo = update_callback()
            message = updateInfo.get('message', message)
            windowTitle = updateInfo.get('title', windowTitle)
            msg.setWindowTitle(windowTitle)
            i = (i + 1) % 8
            l1.setText(ticks[i])
            l2.setText(message)
            l3.setText(" " + ticks[i])
            qApp.processEvents()
            if QTHREAD:
                qt.QThread.msleep(1000)
            else:
                time.sleep(2)
    msg.close()